Async/Await And Promises in Javascript ES6 / ES7 / ES8

Async/Await And Promises in Javascript ES6 / ES7 / ES8

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 async function 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)
Async / Await

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'));
Promises

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.

Rahul Shukla

Rahul Shukla

I'm a Back-End Developer & Hybrid App Developer based in Mumbai, India. ... More Info

Leave a Reply

Your email address will not be published. Required fields are marked *