我有一个具有两个数组作为属性的对象:
我想通过连续运行 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/