Abdul Ahmad
Abdul Ahmad

Reputation: 10021

2 promises run simultaneously when 'return' is not used

If I perform an async operation in JS and I chain 2 .then calls, when I use the return keyword on the async operation in the first .then the execution happens as expected:

  1. first async operation executes after x amount of time
  2. second async operation executes after x amount of time

but, if the async operation in the first .then doesn't explicitly use return, both operations complete at the same time, x amount of time after the initial async operation, example:

scenario 1:

function doAsync() {
  return new Promise(res => {
    setTimeout(() => res('hi'), 3000);
  });
}

doAsync().then(() => {
  console.log('async then 1'); // executes 3 seconds after 
  return doAsync();
}).then(() => {
  console.log('async then 2'); // executes 6 seconds after
});

scenario 2:

function doAsync() {
  return new Promise(res => {
    setTimeout(() => res('hi'), 3000);
  });
}

doAsync().then(() => {
  console.log('async then 1'); // executes 3 seconds after 
  doAsync(); // no return
}).then(() => {
  console.log('async then 2'); // executes 3 seconds after
});

why is this? does return signify to wait for the first promise to resolve before moving on to the second promise? so if return is skipped, the second async operation starts before waiting for the first promise to resolve?

Upvotes: 1

Views: 133

Answers (1)

a1300
a1300

Reputation: 2813

If you omit the return keyword the second doAsync() gets scheduled immediately and the first then exits.

You are not chaining your Promises if you omit the return keyword.

Upvotes: 1

Related Questions