javascript - 如何在特定条件下做出 promise 解决?

标签 javascript promise

我是 JavaScript 的新手,我真的对有关 promise 的文档感到困惑。 我这里有以下案例,我有大量用户,我为每个用户执行一个异步函数,在该函数中我对该用户进行一些计算,并将结果与​​用户一起添加到数组中。根据我从文档中了解到的情况,我需要在每次执行异步函数时获得一个 promise ,并将所有 promise 添加到一个 promise 列表中,当结果数组传递给它时,该 promise 列表如下:

 someFunction = () => {
   var promises = [];
   users.forEach(user => {
       var promise = asyncFunction(user).callback(callBackValue => {
         // Run some checks and add the user to an array with the result
         if (checksAreGood) {
           usersArray.push({user: user, result: callBackValue});
         }
       });
       promises.push(promise);
   });
   return Promise.all(promises).then(() => Promise.resolve(matches));
 };

问题是:如果我遍历的用户数未知,我想将添加到数组的用户数限制为 20,当且仅当用户数超过 20 时,否则添加所有用户。换句话说,当数组充满 20 个或更少的用户时 resolve promise。 这样做的目的是避免为优化性能而给定的全部用户执行异步函数。意思是,如果我有 1000 个用户,我希望执行异步函数,直到数组满到 20 个为止。

最佳答案

第一个只搜索到 20 个用户的解决方案是一个接一个地遍历:

 async function someFunction(){
  const results = [];
  for(const user of users){
     const result = await asyncFunction(user);
     // Run some checks and add the user to an array with the result
     if(!someChecksGood) continue;
     results.push(result);
     if(results.length >= 20) break;
  }
  return results;
 }

虽然这工作“完美”,但它相当慢,因为它一次只处理一个请求。因此,相反的解决方案是一次运行所有请求,如果数组已满则取消它们:

 async function someFunction(){
  const results = [];
  async function process(user){
    const result = await asyncFunction(user);
    if(!someChecksGood || results.length >= 20) return;
    results.push(result);
   }
   await Promise.all(users.map(process));
   return results;
 }

但是现在有大量不必要的请求,之后会被丢弃。为了改善这一点,可以通过“分块”请求来结合上述两种方法,这不应减少请求时间,因为数据库一次只能处理一定数量的请求,但好处是我们可以在以下时间停止处理数组已满,只有其余的“ block ”是不必要的处理,所以平均来说它应该比上面的两种解决方案更好:

  async function someFunction(){
    //Chunk the users
    const chunks = [], size = 5;
    for(var i = 0; i < users.length; i += size)
      chunks.push( users.slice(i, i + size));
    //the method to create the results:
    const results = [];
    async function process(user){
      const result = await asyncFunction(user);
      if(!someChecksGood || results.length >= 20) return;
      results.push(result);
    }
    //iterate over the chunks:
    for(const chunk of chunks){
      await Promise.all(chunk.map(process));
      if(results.length >= 20) break;
    }
    return results;
 }

关于javascript - 如何在特定条件下做出 promise 解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967232/

相关文章:

javascript - SmoothState 和 Wordpress。为玩家和 Google Chart 回调调用什么函数?

javascript - 如何在绑定(bind)中使用 switch 语句?

jQuery Promise().done() 不起作用

javascript - 我可以在 Parse JavaScript SDK 中使用其他 promise 实现吗?

javascript - 元素不占用 child 的宽度

javascript - 如何从 JavaScript 中打开新的浏览器选项卡?

javascript - 仅在 Jquery promise 完成后才执行语句?

angularjs - Promise 链成功在第一个返回错误后执行

javascript - 组内正则表达式惰性匹配?

javascript - Promise 中的 Testcafe Runner