Skip to content Skip to sidebar Skip to footer

Order Of Promise In Javascript

If I call a function ,which returns a Promise object , sequentially several times would the order of execution of those async operations be same as the order in which Promise objec

Solution 1:

It depends on the implementation of the function, and by what you mean by "the execution of those async operations."

Typically, a function returning a promise synchronously starts an asynchronous operation, and that's all it does: Start the operation. The operation then continues and completes independently of the function that started it.

So if you do this:

var p1 = foo(1);
var p2 = foo(2);
var p3 = foo(3);

...and foo synchronously starts an asynchronous operation when you call it, then yes, the async operations will be started in the order the promises were created.

That doesn't mean they continue or complete in that order, and indeed they very well may not. It depends on the operations in question.

Example:

functionfoo(value) {
  returnnewPromise(resolve => {
    console.log("starting " + value);
    setTimeout(function() {
      console.log("completing " + value);
      resolve(value);
    }, value == 2 ? 800 : 200);
  });
}
var p1 = foo(1);
var p2 = foo(2);
var p3 = foo(3);
// Naturaly, in real code, we'd have error handlers on those

foo starts the operations in order, but they complete out of order, because the operation for 2 takes longer than the operations for 1 and 3.

Solution 2:

The order of execution of promises will be the same as the order in which the promises were created, yes but they won't necessarily resolve in the same order. They will resolve whenever their task is completed like api request is completed and we get the data.

Post a Comment for "Order Of Promise In Javascript"