Monday, June 17, 2019

axios async await

Sometimes you need to wait for one (axios) call to finish to continue with next one. It's accomplished by using async/await. Last axios call in app.js downloads a file without waiting for getUser() to be finished.

set server delay to 4 seconds for demo purposes

{
  "name": "async-await",
  "scripts": {
    "serve-json": "json-server --delay 4000 --watch db.json",
    "start": "node app.js"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "json-server": "^0.15.0"
  }
}

db.json

{
    "heroes": [
        {
            "param": "users"
        },
        {
            "param": "1"
        }
    ]
}

app.js

const axios = require('axios')
const fs = require('fs')
 
async function getUser() {
    try {
        console.log("start");
        const response = await axios.get('http://localhost:3000/heroes');
        var1 = response.data[0].param; // users
        console.log("4 sec after start ", var1);
        const response2 = await axios.get('http://localhost:3000/heroes');
        var2 = response2.data[1].param; // 1
        console.log("8 sec after start", var2);
        const response3 = await axios.get('https://jsonplaceholder.typicode.com/' + var1 + '/' + var2);
        console.log(response3.data.name);
    } catch (error) {
        console.error(error);
    }
}
 
getUser()
 
// call below doesnot wait for getUser() to be finished 
axios({
    method: 'get',
    url: 'https://jsonplaceholder.typicode.com/users/2',
    responseType: 'stream'
  })
    .then(function (response) {
      response.data.pipe(fs.createWriteStream('full-user.json'))
});






No comments:

Post a Comment