Async/Await vs new Promise(resolve,reject)

3196 views javascript
2

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?

answered question

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 from similar question

It doesn't make sense to compare your examples. The one defines the functionTahtReturnsPromise, the other calls it and uses the promise?

To answer the question title "Async/Await vs new Promise(resolve,reject)": async/await cannot replace new Promise

3 Answers

6

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.

posted this
1

You're totally 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

posted this
6

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.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories