将 axios 与 async 和 await 一起使用



我是异步和等待生态系统的新手,但我知道它提供了以同步方式编码的方式(尽管它在幕后是异步的,只是用代码编写的方式(。

所以这是我想要以异步方式执行的代码。

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);

现在有一些查询我无法破解,让我们先看看输出:

>>>>>>>>>>> abc Promise { <pending> }
after the call to service
  1. 该行是在执行之后调用服务。为什么?异步等待行为发生了什么变化?

请谈谈一些看法?

提前感谢,祝编码:)愉快。

你需要在另一个异步函数中使用 await 调用getJSONAsync

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

或者调用它并等待返回的承诺解决(即Promise.prototype.then(

好的,在异步等待魔法中多了一点之后,我发现如果你只是尝试一些东西来检查,它会更好,以这种方式:

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);
})();

在这里,我创建了一个异步匿名函数,该函数在创建后立即被调用。如果有人有任何疑问,请告诉我。

仅供参考:这在某种程度上是一个 IIFE,立即调用的函数表达式。

遇到异步调用时,程序的控制权将返回到调用方法,直到异步调用完成。

因此,在您的情况下,您调用异步方法,它发送和异步请求以获取资源并返回到上一个(在调用堆栈上(方法。然后,您尝试记录 abc,在该时间点,abc 仍在获取资源,因此您只需打印一个挂起的承诺。当异步调用最终完成时,控制权将交还给您的 getJSONAsync (( 方法,控制台日志在那里打印消息

将异步函数结果绑定到变量,然后记录变量,当时是未解析的 Promise。当您收到请求的响应时,将显示第二个控制台.log。

为了回答您的问题,async/await 行为仅适用于异步函数内部,不适用于调用此函数等代码的其他部分。

最新更新