自己使用多个for循环或将逻辑委托给promises是否更有表现力? [英] Is it more performant to use several for-loops by themself or to delegated the logic to promises?

查看:65
本文介绍了自己使用多个for循环或将逻辑委托给promises是否更有表现力?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下情况:一个函数获取3个一定长度的数组,其中每个数组都需要进行迭代以找到匹配的对象.找到对象后,for循环会中断,并且不会调用下一个.在这种情况下,无法合并数组.基本上是这样的:

Following scenario: A function gets 3 arrays of a certain length, each one of those needs to be iterated over to find a matching object. When the object is found, the for-loop breaks and the next one isn't called. The arrays can't be merged in this case. Basically like this:

for (let i = 0; i < array1.length; i++) {
  if (array1[i].id == matchingID) {
    returnValue = array1[i];
    break;
  }
}
if (!returnValue) {
  for (let i = 0; i < array2.length; i++) {
    if (array2[i].id == matchingID) {
      returnValue = array2[i];
      break;
    }
  }
}
if (!returnValue) {
  for (let i = 0; i < array3.length; i++) {
    if (array3[i].id == matchingID) {
      returnValue = array3[i];
      break;
    }
  }
}
return returnValue;

在这种情况下,使用诺言会更有效吗,因为那样可以同时处理所有for循环?像这样,在上面的示例中,每个函数调用都执行一个for循环(并解析找到的值):

Would using promises be more efficient in this case, since that way all for-loops can be worked at at the same time? Like this, with each function-call doing one of the for-loops (and resolving the found value) from the example above:

return new Promise((resolve) => {
  this.findMatchingIDInArray1(array1)
    .then(() => resolve(returnValue));
  this.findMatchingIDInArray2(array2)
    .then(() => resolve(returnValue));
  this.findMatchingIDInArray3(array3)
    .then(() => resolve(returnValue));
}) 

哪种方式更有效?有更好的方法吗?谢谢你的帮助!

Which way is more perfomant? Is there better way to do this? Thanks for your help!

推荐答案

在这种情况下,使用诺言会更有效吗,因为那样可以同时处理所有for循环?

Would using promises be more efficient in this case, since that way all for-loops can be worked at at the same time?

不,您误解了诺言的含义.它们是使使用异步代码进行交易的工具.用例中没有异步代码,因此您不能在此处使用Promise.承诺不会使任何事物异步",甚至不会启用类似多线程的并行性.

No, you misunderstood what promises do. They're a tool to make dealing with asynchronous code easier. There is no asynchronous code in your use case, so you cannot make use of promises here. Promises do not "make" anything asynchronous, or even enable multithreading-like parallelism.

这篇关于自己使用多个for循环或将逻辑委托给promises是否更有表现力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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