Reputation: 417
Why do my promises stay in the pending state and how do I fix it?
var foundPeopleA = findPeopleA().then(function(result) {
var res = []
result.map(function(el) {
res.push(getProfileXML(el.sid));
});
return res
});
var foundPeopleB = findPeopleB().then(function(result) {
var res = []
result.map(function(el) {
res.push(getProfileXML(el.sid));
});
return res
})
return Promise.all([findPeopleA, findPeopleB]).then(function(results) {
console.log(results) //[ [ Promise { <pending> }, Promise { <pending> } ], [ Promise { <pending> }, Promise { <pending> } ] ]
})
However if i change the body of the 2 functions above into
var res
result.map(function(el) {
res = getProfileXML(el.sid);
});
return res
they won't be pending and I'll get the result.
Upvotes: 0
Views: 1456
Reputation:
The problem is that you are handling the promises fulfillment on each of them individually by using then
, and all
handles the fulfillment of multiple promises by passing it an array of unresolved promises. It builds a new promise with the results of all of them together. Just use:
Promise.all([findPeopleA(), findPeopleB()])
.then(function(responses) ...
Upvotes: 1
Reputation: 1580
Try assigning your Array to the result of the mapping.
var foundPeopleA = findPeopleA().then(function(result) {
var res = []
res = result.map(function(el) {
return getProfileXML(el.sid);
});
return res
});
Or, perhaps you can resolve the promise?
var foundPeopleA = findPeopleA().then(function(result) {
var res = []
res = result.map(function(el) {
return getProfileXML(el.sid);
});
resolve(res);
});
Either way, I belive you need to build your array by returning values from the mapping to create the new array.
Upvotes: 0
Reputation: 198324
Arrays are not promises. If you return an array of promises, then
gets an array of promises - just like if you return any other non-promise value. Only if you return a promise, the promise will get executed before then
. Your foundPeopleA
and foundPeopleB
each construct an array of promises; you need to concatenate those arrays and pass them to Promise.all
or equivalent in order to get them executed.
Upvotes: 1