(async()=> {})();这是什么? [英] (async () => { })(); what is this?
问题描述
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 () => {})()
是什么意思?
我发现它比
What does it mean to put methods (test1,test2,test3) inside async () => {})()
?
I find it faster than
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);
}
使用它有什么缺点吗?
推荐答案
都返回一个诺言,但它们返回不同的诺言.
Both return a promise but they return different promises.
第一个将返回一个承诺,该承诺可能会在this.test1()
的结果解析之前解决.
The first will return a promise that may resolve before this.test1()
's result resolves.
第二个返回的诺言只有在最终调用this.doThis(a,b,c);
之后才能解决.
The second returns a promise that only resolves after the final call to this.doThis(a,b,c);
.
这被称为" fire and忘记模式":
通常在应用程序开发中,您希望一个进程调用另一个线程并继续该进程流,而不用等待被调用线程的响应.这种模式称为即发即弃"模式.
Often in application development you want a process to call another thread and continue the process flow, without waiting for a response from the called thread. This pattern is called the "fire and forget" pattern.
您可以在
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();
这篇关于(async()=> {})();这是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!