Yesterday, A interviewer asked me this question that "How do you give priority to a promise in JS/NodeJS ?".I was like you could use some thing like await or promise.resolve(), but he said that's not giving priority. Can anyone explain?
So, one possible way of doing this is using setImmediate and process.nextTick()
https://jinoantony.com/blog/setimmediate-vs-process-nexttick-in-nodejs/
setImmediate() and process.nextTick() are two functions which allows us to control the order of execution of our code in the event loop. Both of these functions schedule our callback handlers in the event queue. But they are executed at different phases of the event loop.
you can do promise chaining by this way, to make sure independent promises run in given order one by one:
function later(delay) {
return new Promise(function(resolve) {
setTimeout(resolve(delay), delay);
});
}
//Promise 1:
let p1 = later(100)
//Promise 2:
let p2 = later(200)
//Promise 2:
let p3 = later(300)
p1.then(delay => (console.log(delay))).then(p2.then(delay => console.log(delay)).then(p3.then(delay => console.log(delay))));
//console:
//100
//200
//300
Maybe what he was getting at was that in a pool of promise, priority could be to solely resolve the first one in that pool, which you could do by using Promise.race (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)