JavaScript
JavaScript

Promise in JavaScript is very handy for asynchronous task such as fetching a URL.
Developers who use Promise a lot, often will have to call then() with 1 callback function in it.

promise.then((result) => {});

promise.then(function(result){});

Prior to Promise, developers tend to use callback functions to handle asynchronous call in JavaScript. However, callback functions have potential problem which might lead to an anti pattern known as Callback Hell.

Callback hell is an anti-pattern which consists of multi-nested callback functions. With Promise callback hell can be prevented.

In ES2016, there are these async and await expressions which make Promise based codes look even better in readability. In addition to this, by using async and await, they make codes look as if running in procedural way. Developers do not have to use then() to process the result returned by Promise anymore.

Fetching Data using Promise

promise.js
(() => {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.text())
    .then((text) => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
})();

The above code snippets demonstrates Promise full-fills network request with Fetch API.

Async and Await

asyncawait.js
(async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
})();

The above code snippets demonstrates how async and await full-fills network request. It does exactly the same thing as in promise.js using async and await keywords

To create an async function, a function has async keyword before it. Also await keywords are only valid in async functions. If there is value return from an async function, it will always be a Promise.

References

Async Expression
Fetch API

Last modified: May 23, 2018

Author