(async()=> {})();这是什么?

时间:2019-07-12 20:04:46

标签: 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);                              
  })();
}

将方法(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); 
}

使用它有什么缺点吗?

1 个答案:

答案 0 :(得分:9)

两者都返回一个诺言,但是它们返回不同的诺言。

第一个将返回一个可能会在this.test1()的结果得到解决之前解决的承诺。

第二个返回的诺言只有在最终调用this.doThis(a,b,c);之后才会解决。

这被称为“ 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();