Mandroid
Mandroid

Reputation: 7534

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 objects were created?

Upvotes: 0

Views: 59

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075905

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:

function foo(value) {
  return new Promise(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.

Upvotes: 2

supra28
supra28

Reputation: 1636

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.

Upvotes: 1

Related Questions