在 async 和 await 中使用 axios [英] Using axios with async and await

查看:40
本文介绍了在 async 和 await 中使用 axios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Async 和 await 生态系统的新手,但我知道它提供了以同步方式编码的方式(尽管它在幕后是异步的,只是它在代码中的编写方式).

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

  1. 线路是在调用服务之后在执行之后出现.为什么?异步等待行为发生了什么变化?
  1. 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.

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

这篇关于在 async 和 await 中使用 axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆