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);
})();
}
将方法 (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);
}
使用它有什么缺点吗?
两者都返回一个承诺,但他们返回不同的承诺。
第一个将返回一个可能在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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句