javascript 如何使用 async/await 返回 Ajax 结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48506445/
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
How to return an Ajax result using async/await?
提问by user3599803
Trying to get familiar with async/await, I've tried the following code in Chrome:
为了熟悉async/await,我在 Chrome 中尝试了以下代码:
async function f() {
return await $.get('/');
};
var result = f();
but resultdoesn't hold the result (string); rather it holds a Promisewhich needs to be awaited again. This code does give me the response string:
但result不保存结果(字符串);相反,它持有一个Promise需要再次等待的。这段代码确实给了我响应字符串:
var response = await $.get('/');
How can I return the actual response string from a function using await?
如何使用 await 从函数返回实际的响应字符串?
回答by messerbill
either
任何一个
function f() {
return $.get('/');
};
async test() {
var x = await f()
console.log(x)
}
test()
or
或者
f().then(function(res) {
console.log(res)
}
the async/awaitis just another way to write the same logic.
这async/await只是编写相同逻辑的另一种方式。
回答by samanime
awaitand asyncare basically just syntactical sugar on top of Promise. If you end up with a Promiseat the end, you still need to treat it like a Promise.
await并且async基本上只是Promise. 如果最后以 aPromise结束,您仍然需要将其视为Promise.
const response = f().then(() => { });
Or, if you are calling it inside of an async function, you can await to resolve it:
或者,如果您在异步函数内调用它,您可以等待解决它:
async function main() {
const response = await f();
console.log(response);
}
A pattern I like to use is have my main code wrapped in a self-executing async function, so I can still use await:
我喜欢使用的一种模式是将我的主要代码包装在一个自执行的异步函数中,所以我仍然可以使用 await:
(async () => {
const result = await doSomething();
console.log(result);
})();
Note that even with that pattern, I need a final catch()to catch any errors it may have that aren't caught otherwise:
请注意,即使使用这种模式,我也需要一个 finalcatch()来捕获它可能存在的任何错误,否则不会被捕获:
(async () => {
// blah blah
})().catch(() => {});

