【问题标题】:How to use loop in javascript promises chain [duplicate]如何在javascript承诺链中使用循环[重复]
【发布时间】:2019-07-01 23:25:09
【问题描述】:

我对 JS 比较陌生,无法将承诺概念应用于我拥有的用例,我检查了 this SO 和其他人一样,但无法为我的案例推导出解决方案。 我需要在循环中调用承诺,但只有在循环完成后才应该调用下一个“then”。这在 JS 中是否可行?

function startCooking(ingredients) {
    Utility.startConnection()
        .then(
            function (connectionTime) {             
                for (let [key, plainVector] of ingredients) {
                    encryptIngredients(plainVector)
                        .then(
                            function (encryptedBinary) {
                                return Utility.cookDinner();
                            }
                        ).then(
                            function (dinner) {                             
                                console.log(...);
                            }
                    );
                }
            }
        ).catch(
            ...
        );              
}

function encryptIngredients() {
    return new Promise(...);
}

【问题讨论】:

  • 这绝对是可能的,但也有点难看。您可以使用 async/await 还是必须支持旧版浏览器?
  • 我需要使用vanilla JS并且还支持IE11

标签: javascript promise es6-promise


【解决方案1】:

这就是大致的工作方式。

如果此函数加密单一成分:

function encryptIngredient(ingredient) {

   return new Promise(...);

}

然后这个函数加密一个成分列表:

function encryptIngredients(ingredients) {

   // Note that 'shift' changes the array
   const current = ingredients.shift();
   return encryptIngredient(current).then( () => {
      if (ingredients.length > 0) {
        return encryptIngredients(ingredients);
      }
   });       

}

这是最后一个函数的 async/await 版本。它更简单:

async function encryptIngredients(ingredients) {

   for(const ingredient of ingredients) {
      await encryptIngredient(ingredient);
   }    

}

【讨论】:

  • 哇,亮了,我明天试试,我用的是地图,看看能不能搞定。
  • 递归函数确实有效,因为我使用的是地图,所以我需要使用丑陋的解决方法,而不是使用 for (let [key, plainVector] of ingredients) { currentKey = key;当前向量 = 普通向量;休息};成分.delete(currentKey);但它有效,谢谢。
  • 这是有道理的@David。尝试编写一个通用函数来按顺序迭代一系列 Promise 并将其结果作为数组返回可能会有所帮助。
猜你喜欢
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 2016-07-08
相关资源
最近更新 更多