bbu*_*ver 10 javascript async-await
async function test() {
(async () => {
var a = await this.test1();
var b = await this.test2(a);
var c = await this.test3(b);
this.doThis(a,b,c);
})();
}
Run Code Online (Sandbox Code Playgroud)
将方法(test1,test2,test3)放在里面意味着什么async () => {})()?我发现它比
async function test() {
var a = await this.test1();
var b = await this.test2(a);
var c = await this.test3(b);
this.doThis(a,b,c);
}
Run Code Online (Sandbox Code Playgroud)
使用它有什么缺点?
两者都返回承诺,但它们返回不同的承诺。
第一个将返回一个承诺,该承诺可能会在this.test1()结果解决之前解决。
第二个返回的诺言只有在最终调用时才能解决this.doThis(a,b,c);。
这就是所谓的“ 一劳永逸模式 ”:
通常在应用程序开发中,您希望一个进程调用另一个线程并继续该进程流,而不用等待被调用线程的响应。这种模式称为“即发即弃”模式。
你可以在这里看到
function logEventually(str) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(str);
resolve(null);
}, 0);
});
}
async function a() {
await logEventually('in a 1');
await logEventually('in a 2');
await logEventually('in a 3');
return await logEventually('end of a');
}
async function b() {
(async () => {
await logEventually('in b 1');
await logEventually('in b 2');
await logEventually('in b 3');
})();
return await logEventually('end of b');
}
a();
b();Run Code Online (Sandbox Code Playgroud)