如何使用 async/await 返回 Ajax 结果? [英] How to return an Ajax result using async/await?
本文介绍了如何使用 async/await 返回 Ajax 结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了熟悉 async/await
,我在 Chrome 中尝试了以下代码:
Trying to get familiar with async/await
, I've tried the following code in Chrome:
async function f() {
return await $.get('/');
};
var result = f();
但是 result
不保存结果(字符串);相反,它持有一个需要再次等待的 Promise
.此代码确实给了我响应字符串:
but result
doesn't hold the result (string); rather it holds a Promise
which needs to be awaited again. This code does give me the response string:
var response = await $.get('/');
如何使用 await 从函数返回实际的响应字符串?
How can I return the actual response string from a function using await?
推荐答案
要么
function f() {
return $.get('/');
};
async test() {
var x = await f()
console.log(x)
}
test()
或
f().then(function(res) {
console.log(res)
}
async/await
只是编写相同逻辑的另一种方式.
the async/await
is just another way to write the same logic.
这篇关于如何使用 async/await 返回 Ajax 结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文