Tuesday, July 3, 2018

Using Axios In the Loop With Async/Await Promise

With Babel now supporting async/await out of the box, and ES2016 (or ES7) just around the corner, more and more people are realizing how awesome this pattern is for writing asynchronous code, using synchronous code structure.

1. Every async function you write will return a promise, and every single thing you await will ordinarily be a promise.
2. Async/await is a new way to write asynchronous code.
3. Async/await is actually built on top of promises. It cannot be used with plain callbacks or node callbacks.
4. Async/await is, like promises, non blocking.
5. Async/await makes asynchronous code look and behave a little more like synchronous code. This is where all its power lies.

In the following example we are using Axios to fetch the data and using for loop with Async/Await promise to print the title of the posts. The result is sequentially logged one by one after each Promise resolved.
const axios = require('axios');

const getTitle = (num) => {
  return new Promise((resolve, reject) => {
    .then(response => {
      return resolve(response.data.title)
    .catch(error => {
      return reject(error.message)

const start = async() => {
  for (let num of [1, 2, 3, 4, 5]) {
    await getTitle(num).then((title) => {
      console.log(`num ${num}: ${title}`);


// ---
// num 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
// num 2: qui est esse
// num 3: ea molestias quasi exercitationem repellat qui ipsa sit aut
// num 4: eum et est occaecati
// num 5: nesciunt quas odio
// Done

Some things to note:
1. Our function has the keyword async before it. The await keyword can only be used inside functions defined with async. Any async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function (which is the string "response.data.title" in our case).
2. await getTitle(num) means that the console.log call will wait until getTitle(num) promise resolves and print it value.

6 Reasons Why JavaScript’s Async/Await Blows Promises Away
Loop with async and await in JavaScript

No comments:

Post a Comment