2

Let's say I have the following async function. The console.log will only fire after it has been resolved.

(async () => {
  await new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });
  console.log('resolved');
})();

Is this valid JavaScript? Or should I always use .then()? What are the drawbacks or behavioral differences from using .then() here?

(async () => {
  return await new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });
})().then(() => {
  console.log('resolved');
});

Off-topic: I also noticed the latest method return await can be changed to just return without the results changing, but this thread answered that question.

Daan
  • 2,680
  • 20
  • 39

1 Answers1

3

Being able to handle asynchronous operations without always resorting to then is the main point of async/await. The first example is perfectly valid.

The second one is a bit of an antipattern as it would be functionally identical without the async/await for two reasons - marking your function with async implicitly makes it return a Promise, but you also explicitly return one - and awaiting the Promise causes the code to wait until the Promise resolves before returning it, but since you are chaining with then, the then doesn't run before the Promise resolves anyway.

This would be functionally identical:

(() => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });
})().then(() => {
  console.log('resolved');
});

The main drawback of using "synchronous-like" code like the first example is error handling - if you do 5 await operations in a row and any of them reject, your whole async function returns a rejected Promise. If you chain then operations, you can also insert catch handlers to handle specific error cases with more precision.

Daan
  • 2,680
  • 20
  • 39
jlaitio
  • 1,878
  • 12
  • 13
  • Is it really a drawback since you can put try/catch blocks around whatever await-ed operations you have in a row? – ADJenks Jul 16 '19 at 21:24