将Async/Await响应保存在变量上 [英] Save Async/Await response on a variable

查看:152
本文介绍了将Async/Await响应保存在变量上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用async/await和try/catch了解异步调用.

I am trying to understand async calls using async/await and try/catch.

在下面的示例中,如何保存对变量的成功响应,该变量可以在其余的代码中使用?

In the example below, how can I save my successful response to a variable that can be utilized throughout the rest of the code?

const axios = require('axios');
const users = 'http://localhost:3000/users';

const asyncExample = async () =>{
    try {
        const data = await axios(users);
        console.log(data); //200
    }
    catch (err) {
        console.log(err);
    }
};

//Save response on a variable
const globalData = asyncExample(); 
console.log(globalData) //Promise { <pending> }

推荐答案

1)从您的asyncExample函数返回一些内容

1) Return something from your asyncExample function

const asyncExample = async () => {
  const result = await axios(users)

  return result
}

2)调用该函数并处理其返回的Promise:

2) Call that function and handle its returned Promise:

;(async () => {
  const users = await asyncExample()
  console.log(users)
})()

这就是为什么要这样处理:

Here's why should you handle it like this:

  • 您不能做顶级await(有提案尽管如此); await必须存在于async函数中.
  • You can't do top-level await (there's a proposal for it though); await must exist within an async function.

但是我必须指出,您的原始示例不需要async/await 根本由于axios已经返回了Promise,因此您只需执行以下操作:

However I must point out that your original example doesn't need async/await at all; Since axios already returns a Promise you can simply do:

const asyncExample = () => {
  return axios(users)
}

const users = await asyncExample()

这篇关于将Async/Await响应保存在变量上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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