为了熟悉async/await
,我在 Chrome 中尝试了以下代码:
async function f() {
return await $.get('/');
};
var result = f();
但result
不保存结果(字符串);相反,它持有一个Promise
需要再次等待的。这段代码确实给了我响应字符串:
var response = await $.get('/');
如何使用 await 从函数返回实际的响应字符串?
为了熟悉async/await
,我在 Chrome 中尝试了以下代码:
async function f() {
return await $.get('/');
};
var result = f();
但result
不保存结果(字符串);相反,它持有一个Promise
需要再次等待的。这段代码确实给了我响应字符串:
var response = await $.get('/');
如何使用 await 从函数返回实际的响应字符串?
任何一个
function f() {
return $.get('/');
};
async test() {
var x = await f()
console.log(x)
}
test()
或者
f().then(function(res) {
console.log(res)
}
这async/await
只是编写相同逻辑的另一种方式。
await
并且async
基本上只是Promise
. 如果最后以 aPromise
结束,您仍然需要将其视为Promise
.
const response = f().then(() => { });
或者,如果您在异步函数内调用它,您可以等待解决它:
async function main() {
const response = await f();
console.log(response);
}
我喜欢使用的一种模式是将我的主要代码包装在一个自执行的异步函数中,所以我仍然可以使用 await:
(async () => {
const result = await doSomething();
console.log(result);
})();
请注意,即使使用这种模式,我也需要一个 finalcatch()
来捕获它可能存在的任何错误,否则不会被捕获:
(async () => {
// blah blah
})().catch(() => {});
异步函数的返回类型是 Promise。所以你必须等待或 then() 才能得到结果。