javascript - 将 Promise 函数映射到数组不会保留结果

标签 javascript arrays promise

我有一个具有两个数组作为属性的对象:

我想通过连续运行 Promise 来填充数组。 我获取 promise 的结果,并映射一个函数来装饰数组中的所有项目。

当一个数组被填充并保留时,另一个数组仅在 map 函数中被填充,但最后返回的数组仍然为空。

你能帮助理解为什么吗?

我检查 Promise 是否确实返回,并且确实在一种情况下有效,而在另一种情况下则无效。

这是我的伪代码:

function formatMyObject( arrayOfIds ) {

// initialize the objet
var myObj = {
   decorators = [],
   nodes = []
   ...
}

// I map the Promise reconciliate() and push the results in the array:

return reconciliateNode(arrayOfIds)
       .then( data => { 
             data.map( node => {
                //  I fetch results, and   myObj.nodes

             myObj.nodes.push( { ...   })
            })

       })

     return myObj
    })
   .then( myObj => {

      // myObj.nodes is now a NON empty array

      // I want to the same with myObj.decorators:

      var data = myObj.nodes

      // I think I am doing just as above:

      data.map( node => 
          decorateNode(node.source)
            .then( decoration => {

              decoration = decoration[node.source]

              myObj['decorators'].push( {
                    ... 
              } )

              // I check: the array is NOT empty and getting populated:
              console.log('myObj.decorators', myObj)
              debugger
          })
    )

    // instead now, just after the map() function, myObj.decorators is EMPTY!
    console.log('myObj.decorators', myObj);
    debugger


    return myObj
)

... // other stuff
}

最佳答案

与第二种情况一样,map回调返回一个promise,这种情况与第一种情况有很大不同。

在第二种情况下,您需要等待所有这些 Promise,对此您可以使用 Promise.all

第二部分的代码可能如下所示:

.then( myObj => {
    return Promise.all(myObj.nodes.map(node => decorateNode(node.source)));
}).then(decorations => {
    myObj.decorators = decorations.map(decoration => {
        decoration = decoration[node.source];
        return ({
            ... 
        });
    })
    console.log('myObj.decorators', myObj);
    return myObj;
})

关于javascript - 将 Promise 函数映射到数组不会保留结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600332/

相关文章:

javascript - 从javascript中的多维数组中获取所有变体

javascript - 访问 promise 回调中对象的 'this'(然后)

javascript - NodeJS Promises 无法编辑现有的 'model'

java - 如何对合法 Action 进行硬编码以进行快速查找?

c - 传递给函数的结构数组,取消引用 -> 和 * 之间的区别

javascript - 了解里面 this 的用法

javascript - 使用 ajax 和 GET 在 DataTable 中使用 MySQL 结果

javascript - 带有表单标签的 ASP.NET Core - 验证表单 onsubmit 并阻止提交

javascript - dataTables:删除除一个选择输入外的所有输入

javascript - 仅当 Angular2/ionic2 中的 Promise 得到解析时才执行 Observble