簡體   English   中英

將Promise函數映射到數組不會持久保存結果

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

我有一個帶有兩個數組的對象作為屬性:

我想通過連續運行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.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;
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM