0

I am reviewing some code, it looks like this:

const doTwoThings = async() => {
  const { foo } = await doThingA();
  return await doThingB(foo);
}

I would re-write this as

const doTwoThings = () => {
  return doThingA().then(({ foo }) => 
    doThingB(foo);
  );
}

Is there any difference between these two (performance, error handling, etc)? Or is it just my stylistic preference?

Jonny
  • 2,509
  • 23
  • 42
  • 2
    No difference at all; async/await is just syntactic sugar for promises, they're interoperable. – jonrsharpe Nov 24 '20 at 09:41
  • Excellent dupetarget, so I've converted my answer to a comment: `async`/`await` are syntax that allow you to produce and consume promises using the same logical constructs you're used to, rather than callback functions. There are some minor differences in your two examples, but nothing of import. They fundamentally do the same thing. (Note that you don't need the `await` in `return await doThingB(foo);` in your example. Unless you have that in a `try` block and want to catch rejection from `doThingB`'s promise within its `catch` inside the function, just `return doThingB(foo);` is sufficient.) – T.J. Crowder Nov 24 '20 at 09:45
  • Early on, implementations of `async`/`await` were less efficient than well-written code consuming the promises with callbacks, but that didn't last long as JavaScript engine implementers optimized things. :-) (FWIW, I go into promises and `async`/`await` in a fair bit of detail, including showing a full translation of an `async` function into `.then` etc. calls, in Chapters 8 and 9 of my new[ish] book, *JavaScript: The New Toys* in Chapters 8 [promises] and 9 [`async` functions]. Links in my profile if you're interested.) – T.J. Crowder Nov 24 '20 at 09:47

0 Answers0