Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does using async/await differ from using Promises?

Recently I started using (Async & Await). Before this, I used Promise to make my process Asynchronous. Like:

example.firstAsyncRequest()
.then(firstResponse => {
    return example.secondAsyncRequest(firstResponse)
})
.then(secondResponse => {
    return example.thirdAsyncRequest(secondResponse)
})
.then(result => {
    console.log(result)
})
.catch(err => {
    console.log(err)
})

Now I am achieving this like:

  try {
    const firstResponse = await example.firstAsyncRequest();
    const secondResponse = await example.secondAsyncRequest(firstResponse);
    const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
    console.log(thirdAsyncRequest)
  }
  catch (error) {
    // Handle error
  }

In both, the code-block method executes one after another and finally throws an error if any and gets caught by catch block. My question is, is this only a difference of syntax? Please explain or suggest me any link to understand this better.

Thank You

like image 776
Pushpendra Kumar Avatar asked Feb 05 '18 13:02

Pushpendra Kumar


1 Answers

Is there only difference of syntax?

Yes. Your examples are functionally equivalent except that your second example is missing

console.log(thirdAsyncRequest);

...after the third await. (That variable really should be result to match the first code block, or thirdResponse to match the other two response variables).

async/await is syntactic sugar around promise creation and consumption. It's really helpful sugar, but that's all it is. async functions return promises. await expressions let you wait for a promise to settle, either getting the fulfillment value if it's fulfilled or throwing an error if it's rejected. (Since rejections are errors, you can use try/catch to handle them.) An uncaught error in an async function (whether a synchronous error or a promise rejection observed by await) causes the promise the async function returned to be rejected with that error. Otherwise, the function's promise is resolved to whatever the function's code returns: if it returns a non-thenable, the promise is fulfilled with that value; if it returns a thenable, the promise is fulfilled or rejected based on the settlement of that thenable.

(Re "resolve" vs. "fulfill" and such, I've written up this post on promise terminology.)

like image 144
T.J. Crowder Avatar answered Sep 21 '22 06:09

T.J. Crowder