(async()=> {})(); vs回调 [英] (async () => { })(); vs callback

查看:323
本文介绍了(async()=> {})(); vs回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async function test() {
  for (var i = 0; i < balance; i++) {      
    (async () => {            
      var a = await this.test1(i);
      var b = await this.test2(a);
      var c = await this.test3(b);  
      this.doThis(a,b,c);                              
    })();
  }
}

所以我得出的结论是(async () => {})();与一个好的旧回调非常相似

So I've concluded that (async () => {})(); is quite similar to a good old callbacks

function test() {
  for (var i = 0; i < balance; i++) {      
    test1().call().then((a) => {           
      test2().call(a).then((b) => {
        test3().call(b).then((c) => {
           this.doThis(a,b,c);   
         });
      });
    });
  }
}

这是对的吗?在性能方面,我发现它们大致相同.

Is this right? performance-wise I find they are about the same.

  1. 它们有什么区别吗?
  2. 我应该遵循哪种模式?

我想使用第一个async/await,但是如果我拿出(async () => {})();,我发现在UI中呈现内容的速度比第二个要慢.

I want to go with the first one async/await, but if I take out (async () => {})(); I find it slower to render stuff in UI compare to the second one.

推荐答案

它们有什么区别吗?

Do they have any differences?

您应该从then回调中return,以便正确传播错误.除此之外,它们基本上是相等的.

You should return from the then callbacks so that errors do propagate properly. Apart from that, they're basically equal.

我应该遵循什么模式?

What pattern should I follow?

它们都是即发即忘呼叫,您不应忘记对其进行呼叫 处理错误!

Both of them are fire-and-forget calls, on which you should not forget to handle errors!

我想和async/await一起去,但是如果我拿出(async () => {})();,我会发现它变慢了

I want to go with the async/await, but if I take out (async () => {})(); I find it slower

好的,因为那样的话您会进入循环中,因此它将变得有序.

Sure, because then you are awaiting in the loop so it's becoming sequential.

这篇关于(async()=&gt; {})(); vs回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆