【问题标题】:(async () => { })(); what is this?(异步 () => { })();这是什么?
【发布时间】:2019-07-13 04:42:23
【问题描述】:
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); 
}

使用它有什么缺点吗?

【问题讨论】:

  • 它似乎更快,因为返回的承诺实际上并没有等待您的任何顺序逻辑。您不妨将其更改为同步函数,因为在第一种情况下返回的承诺基本上是 return Promise.resolve();,这根本没有用。
  • 如果一点用都没有,什么时候应该使用(async () => { })();
  • 在顶层,当您想要访问 async / await 语法时。如果该表达式存在于另一个函数中,则意味着该函数的调用者将无法知道异步调用何时完成。

标签: javascript async-await


【解决方案1】:

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

第一个将返回一个可能在this.test1() 的结果解析之前解析的promise。

第二个返回一个仅在最终调用 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();

【讨论】:

  • 谢谢。仍然不确定什么时候应该使用(async () => {})();
  • 所以如果它在解析this.test1(); 之前解析this.doThis(a,b,c);,是否意味着this.doThis(a,b,c); 会出错?
  • @bbusdriver 我添加了关于“即发即弃”模式的注释。我认为它符合您的示例中发生的情况。
  • @MikeSamuel 关于“一劳永逸”模式,外部函数通常不是同步的吗?它没有理由返回实际上不等待任何东西的承诺。
  • @bbusdriver。整体返回的 Promise 可能在 test1 解析之前解析。内部 lambda 中的等待链仍然按照 await 语句所暗示的顺序进行。
猜你喜欢
  • 2015-07-21
  • 2017-01-03
  • 2021-02-03
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
相关资源
最近更新 更多