简体   繁体   English

将Promise函数映射到数组不会持久保存结果

[英]mapping a Promise function to an array does not persist results

I have an object with two arrays as properties: 我有一个带有两个数组的对象作为属性:

I want to populate the arrays by running promises in series. 我想通过连续运行promise来填充数组。 I fetch the result of the promises, and map a function to decorate all the items in my arrays. 我获取了promise的结果,并映射了一个函数来修饰数组中的所有项目。

While one array get populated and persist, the other get populated only while in the map function, but at the end the array is returned still empty. 虽然填充了一个数组并保留了该数组,但另一个数组仅在map函数中填充了,但最后该数组仍返回为空。

Can you help to understand why? 你能帮助理解为什么吗?

I check the Promise is actually returned, and indeed in one case it works, not in the other. 我检查Promise是否实际上已返回,并且确实在一种情况下有效,而在另一种情况下却没有。

this is my pseudo-code: 这是我的伪代码:

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
}

As in the second case the map callback returns a promise, that case is quite different from the first case. 与第二种情况一样, map回调函数返回一个Promise,这种情况与第一种情况完全不同。

In the second case, you would need to await all those promises, for which you can use Promise.all . 在第二种情况下,您需要等待所有这些承诺,您可以使用Promise.all

The code for the second part could look like this: 第二部分的代码如下所示:

.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;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM