Follow by Email

Async/Await & Promises in Javascript ES6



What is Async:

Async functions enable us to write promise-based code as if it were synchronous, but without blocking the execution thread. It operates asynchronously via the event-loop.

What is Await:

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the asyncfunction block wait and not the whole program execution.
async function loadJson(url) { // (1)
  let response = await fetch(url); // (2)

  if (response.status == 200) {
    let json = await response.json(); // (3)
    return json;
  }

  throw new Error(response.status);
}

loadJson('no-such-user.json')
  .catch(alert); // Error: 404 (4)

What is Promise:

A promise is an object that may produce a single value some time in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}delay(3000).then(() => alert('runs after 3 seconds'));

Conclusion :

One of the hardest things about writing good JavaScript is dealing with heavily nested asynchronous code. Promises were created to solve the problem with callback hell, but there are still plenty of nested problems related to promises. This is where async/await comes in.
JavaScript added async/await to allows developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write.

Async/Await & Promises in Javascript ES6 Async/Await & Promises in Javascript ES6 Reviewed by RS Coder on April 22, 2020 Rating: 5

No comments:

Disqus Shortname

banner image
Powered by Blogger.