0

Is there any differences between async/await, and more standard promise notations using .then, .finally, and .catch

for example

functionThatReturnsPromise(someVar).then((returnedValueFromPromise) => {
    console.log(returnedValueFromPromise)
})

vs

async functionThatReturnsPromise(someVar)  {
    await returnedValueFromPromise
}

I'm unsure if Promise chaining is just the old notation, and it's been replaced by the newer async/await. Is there still a use case for both? What is better practice?

stktrc
  • 1,599
  • 18
  • 30
  • async await is just syntactically sugar for promise, its makes code look more readable especially when you have nested pomises check out this nice [answer](https://stackoverflow.com/a/34401662/3521116) from similar question – warl0ck Nov 04 '18 at 11:52
  • It doesn't make sense to compare your examples. The one *defines* the `functionTahtReturnsPromise`, the other *calls* it and uses the promise? – Bergi Nov 04 '18 at 11:55
  • To answer the question title "*Async/Await vs new Promise(resolve,reject)*": [`async`/`await` cannot replace `new Promise`](https://stackoverflow.com/q/45788934/1048572) – Bergi Nov 04 '18 at 11:59
  • Isn't Async/Await just an API for better legibility that is using Promises (and generators?) under the hood? – HynekS Nov 04 '18 at 12:10

3 Answers3

2

It all depends on what you want. async/await are new. Think of it this way, they allow a promise to run like it was synchronous when it isn't.

Moreover using async/await makes your code cleaner and more readable. And to answer your question, there are not much differences between them in terms of what they do. The syntax is just quite different.

Promise chaining is not old fashion, they are quite new, just that async/await came a bit later - giving you a "better" way of handling Promises.

Finally, you can use them interchangeably in your code.

codejockie
  • 9,020
  • 4
  • 40
  • 46
2

You're misunderstanding how it works. With async/await you have a synchronous syntax flow of the code execution that's it:

try {
  const returnedValueFromPromise = await functionThatReturnsPromise(someVar);
} catch (err) {
  console.error(err);
  throw err
}

Notice that

  • Code block must be inside an async scoped function
  • You still need to do err handling, can't assume promise will always work good
  • All values returned by async enclosed function are promises by default
diegoaguilar
  • 8,179
  • 14
  • 80
  • 129
1

Something to be careful with await, is that you'll need to wrap await statements in a try catch block in case the request fails which I personally think is uglier than regular promise chaining.

Jacob
  • 524
  • 5
  • 18
  • 2
    You don't need to wrap everything in `try`/`catch` just like you don't have to install a `.catch()` handler on every promise. You just need to do it where you want to handle errors, usually in the end. – Bergi Nov 04 '18 at 11:57