Jam*_*Lin 7 javascript asynchronous async-await
仅仅阅读了本教程,它就使我难以理解为什么await仅在async功能上起作用。
从教程中:
如前所述,await仅在异步功能内起作用。
据我了解,async将函数返回对象包装到Promise中,以便调用者可以使用.then()
async function f() {
return 1;
}
f().then(alert); // 1
Run Code Online (Sandbox Code Playgroud)
而await只是等待诺言在async功能内解决。
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait till the promise resolves (*)
alert(result); // "done!"
}
f();
Run Code Online (Sandbox Code Playgroud)
在我看来,它们的用法没有关系,有人可以解释吗?
await- 我们不知道返回什么什么await做除了等待承诺的决心是,它会立即返回代码执行给调用者。之后函数内的所有代码await都是异步的。
async 是返回承诺的语法糖。await,那么异步代码中的明智选择是什么?我们看下面的错误代码,看看返回值的问题:
function f() {
// Execution becomes asynchronous after the next line, what do we want to return to the caller?
let result = await myPromise;
// No point returning string in async code since the caller has already moved forward.
return "function finished";
}
Run Code Online (Sandbox Code Playgroud)
相反,我们可以问另一个问题:为什么我们没有同步版本await,不会将代码更改为异步?
我的看法是,出于许多充分的理由,使异步代码同步在设计上变得很困难。例如,当等待异步函数返回时,人们很容易意外地使整个应用程序冻结。
用async和进一步说明运行时顺序await:
async function f() {
for(var i = 0; i < 1000000; i++); // create some synchronous delay
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
console.log("message inside f before returning, still synchronous, i = " + i);
// let's await and at the same time return the promise to the caller
let result = await promise;
console.log("message inside f after await, asynchronous now");
console.log(result); // "done!"
return "function finished";
}
let myresult = f();
console.log("message outside f, immediately after calling f");
Run Code Online (Sandbox Code Playgroud)
控制台日志输出为:
message inside f before returning, still synchronous, i = 1000000
message message outside f, immediately after calling f
message inside f after await, asynchronous now
done!
Run Code Online (Sandbox Code Playgroud)