首页 > 解决方案 > 另一个 Promise 的 .then() 内的 for-each 循环内的 Promise 链

问题描述

在 JavaScript 中,我调用了一个返回 id 的 promise;我们称之为promise1。promise1 有一个跟随.then()它,给定从 promise1 返回的 id,调用一个 for-each 循环。在此循环的每次迭代中,promise2执行

promsie2有一个.then(). 所以可以利用promise2返回的数据。

我的代码.js

exports.my_function = (req, res) => {
    var data = req.body;
    var name_array = ["Jeff", "Sophie", "Kristen"]
    var personal_ID_arr = []
    
    promise1.getID(data)    //promise1 gets an int 'id'
       .then(id => {
          array.forEach(name => {      //for each name
              promise2.getPersonalID(name, id)    //promise2 creates a personal id for each person using their name and the id generated from promise1
                  .then(personalID => {
                      personal_ID_arr.push(personalID)  //add the generated personal id to an arr
                   })
           })
        })

   //will need to operate on 'personal_ID_arr' here after the above finishes or possibly still within the promise1's .then; as long as the arr is filled fully
 }

但是,我遇到了同步性问题,不允许这种类型的逻辑发生,因为一旦进入程序的循环方面,事情就会开始乱序发生。在执行这些承诺之后,我还需要使用填写的“personal_ID_arr”执行另一个功能

我已经查看了有关 Promise 链接的其他问题,但这是一个不同的情况,因为 for 循环需要处理来自第一个 Promise 的数据并在 .then() 中使用 .then()。当然,如果存在更好的结构,我不需要保留这种结构。

任何帮助将不胜感激

标签: javascriptasynchronouspromisesynchronizationes6-promise

解决方案


保留一个异步操作将填充的 ID 数组并不能帮助您以后在数组上执行更多异步操作。相反,请考虑为每个名称使用一组 Promise,并等待它们全部使用 Promise.all 解决。此外,我从函数 my_function 变量中删除了personal_ID_arr 并将其移至适当的异步操作。我做了一个简单的数组控制台日志,你应该在那里填写你的下一步。

虽然也许你需要用 Promises 编写这个逻辑,但我建议使用 async / await 来完成这个任务,它会导致代码更具可读性。

exports.my_function = (req, res) => {
var data = req.body;
var name_array = ["Jeff", "Sophie", "Kristen"]

promise1.getID(data)    //promise1 gets an int 'id'
   .then(id =>
      //map the array of Strings to array of Promises instead, wait for them to resolve
      Promise.all(name_array.map(name =>      
          promise2.getPersonalID(name, id) 
       ))
    )
    .then(personal_ID_arr => console.log(personal_ID_arr))


 //will need to operate on 'personal_ID_arr' here after the above finishes or possibly still within the promise1's .then; as long as the arr is filled fully
 }

推荐阅读