How is using async / await different than using promises?

I recently started using (Async and Await). Before that, I used Promise to make my process asynchronous. How:

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 achieve this as:

  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 cases, the code-block method is executed one after another and, finally, throws an error, if any, and falls into the block catch. My question is: is this just the syntax difference? Please explain or offer me any link in order to understand this better.

thank

+4
source share
1 answer

Is there any difference in syntax?

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

console.log(thirdAsyncRequest);

... await. ( result thirdResponse, ).

async/await . , . async return promises, await then, try/catch await catch.

+7

Source: https://habr.com/ru/post/1693193/


All Articles