Javascript 在变量上保存异步/等待响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48327559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save Async/Await response on a variable
提问by Jonca33
I am trying to understand async calls using async/await and try/catch.
我正在尝试使用 async/await 和 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> }
回答by nicholaswmin
1) Return something from your asyncExamplefunction
1)从你的asyncExample函数中返回一些东西
const asyncExample = async () => {
const result = await axios(users)
return result
}
2) Call that function and handle its returned Promise:
2)调用该函数并处理其返回的Promise:
;(async () => {
const users = await asyncExample()
console.log(users)
})()
Here's why should you handle it like this:
这就是为什么你应该这样处理它:
- You can't do top-level
await(there's a proposalfor it though);awaitmust exist within anasyncfunction.
- 你不能做顶级
await(虽然有一个提案);await必须存在于async函数中。
However I must point out that your original example doesn't need async/awaitat all; Since axiosalready returns a Promiseyou can simply do:
但是我必须指出,您的原始示例根本不需要async/await;由于axios已经返回 aPromise您可以简单地执行以下操作:
const asyncExample = () => {
return axios(users)
}
const users = await asyncExample()
回答by guest271314
try..catchcreates a new block scope. Use letto define databefore try..catchinstead of const, returndatafrom asyncExamplefunction call
try..catch创建一个新的块作用域。使用let定义data之前try..catch,而不是const,returndata从asyncExample函数调用
(async() => {
const users = 123;
const asyncExample = async() => {
let data;
try {
data = await Promise.resolve(users);
} catch (err) {
console.log(err);
}
return data;
};
//Save response on a variable
const globalData = await asyncExample();
console.log(globalData);
// return globalData;
})();
回答by Juan
I had same issue with you and found this post. After 2 days of trying I finally found a simple solution.
According to the document of JS, an asyncfunction will only return a Promiseobject instead of value. To access the response of Promise, you have to use .then()method or awaitwhich can return the resulting object of Promise is instead of Promise itself.
To change variables from await, you have access and change the variable you want to assign within the async function instead of return from it.
我和你有同样的问题,找到了这篇文章。经过2天的尝试,我终于找到了一个简单的解决方案。
根据JS 的文档,一个async函数只会返回一个Promise对象而不是值。要访问 的响应Promise,您必须使用.then()方法 or awaitwhich 可以返回 Promise 的结果对象,而不是 Promise 本身。
要从 更改变量await,您可以访问并更改要在异步函数中分配的变量,而不是从中返回。
//Save response on a variable
var globalData;
const asyncExample = async () =>{
try {
const data = await axios(users);
globalData = data; // this will change globalData
console.log(data); //200
}
catch (err) {
console.log(err);
}
};
asyncExample();
But if you do this, you may get an undefined output.
但是如果你这样做,你可能会得到一个未定义的输出。
asyncExample();
console.log(globalData) //undefined
Since asyncExample()is an asyncfunction, when console.logis called, asyncExample()has not finished yet, so globalDatais still not assigned. The following code will call console.logafter asyncExample()was done.
由于asyncExample()是一个async函数,什么时候console.log被调用,asyncExample()还没有结束,所以globalData还是没有赋值。下面的代码将调用console.log后asyncExample()已完成。
const show = async () => {
await asyncExample();
console.log(globalData);
}
show();
回答by Mike Tung
Because the events are happening asynchronously you need to tie in a callback/promise. I'm going to assume it returns a promise.
因为事件是异步发生的,所以你需要绑定一个回调/承诺。我将假设它返回一个承诺。
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().then( (success, err) => {
if (err) { console.error(err); }
console.log(success)
}
回答by Tudor
Just use a callback/promise (cascading programming):
只需使用回调/承诺(级联编程):
axios(users).then(function(response) {
const globalData = response;
console.log(globalData)
});

