Using axios with async and await

情到浓时终转凉″ 提交于 2019-12-03 20:35:59

You either need to call getJSONAsync within another async function with await:

async function main() {
    let abc = await getJSONAsync();
    console.log(abc);
    // ...
}

 main();

or call it and wait for the returned promise to resolve (ie. with Promise.prototype.then)

When you encounter an async call, the control of your program is returned to the calling method, until the async call completes.

So in your case, you call your async method, it sends and async request to get the resource and returns to the previous (on the callstack) method. In that methos, you then try to log abc, which, at that point in time, is still getting the resource, so you just print a pending promise. When the async call finally finishes, control is given back to your getJSONAsync () method and the console log there prints the message

Ok, after going a bit more inside the async-await magic I found that it would be better, if you are just trying some stuff to check, in this manner:

const axios = require("axios");
async function getJSONAsync(){
  let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
  console.log('after the call to service');
  return json;
}

(async()=>{
   let abc = await getJSONAsync();
   console.log('>>>>>>>>>>> abc', abc);
})();

Here I have created an async anonymous function that is being called just after its creation. Please let me know in case anyone has any doubt.

You bind async function result to variable and then log the variable, which at the time is unresolved Promise. When you get response from your request, second console.log appears.

To answer your question, the async/await behaviour is applied only inside async function, not in other parts of code that call this function etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!