将axios与async和await一起使用 [英] Using axios with async and await
问题描述
我是Async的新手,它正在等待生态系统,但是我知道它提供了一种同步方式的编码方式(尽管它在后台是异步的,只是它的代码编写方式).
I am new in Async and await ecosystem, but I know that it gives the way of coding in a synchronous way (although it is async behind the scenes, just the way it is written in code).
这是我想以异步方式执行的代码.
So here is my code that I want to do in an async fashion.
const axios = require("axios");
async function getJSONAsync(){
// The await keyword saves us from having to write a .then() block.
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
console.log('after the call to service');
// The result of the GET request is available in the json variable.
// We return it just like in a regular synchronous function.
return json;
}
let abc = getJSONAsync();
console.log('>>>>>>>>>>> abc', abc);
现在有一些我无法破解的查询,让我们首先查看输出:
Now there are some of the queries that I am unable to crack, let us see the output first:
>>>>>>>>>>> abc Promise { <pending> }
after the call to service
- 该行是在执行后致电服务之后.为什么?异步等待行为发生了什么?
- The line is after the call to service came after the execution. Why? What happened to the async-await behavior?
请发表一些看法?
预先感谢您,并祝您编码愉快:)
Thank in advance, and happy coding :).
推荐答案
好吧,在深入研究 async-await 魔术之后,我发现这样做会更好,如果您只是尝试以这种方式检查一些东西:
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.
这篇关于将axios与async和await一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!