Reputation: 329
I am having issue with capturing each id from queryArray and storing it with the return promise results.
getSavedQueries: function(req, res) {
SPromise.then(function(client) {
const SavedQuery = client.Reports;
var queryArray = req.query.queryArray; // ['123', '234', '456']
var payloadObj = {};
var actions = lo.map(queryArray, function(id) {
var queryID = Number(id);
*payloadObj['ID'] = queryID;* <--- not sure where to put this
return SavedQuery.findOne(queryID).then(function(result){
payloadObj['query'] = result;
return payloadObj
});
});
return Promise.all(actions);
}).then(function(result){
return res.json(result)
});
}
my res.json(result) returns with the last item on the array for all three objects:
[ {ID: 456, query: ...},
{ID: 456, query: ...},
{ID: 456, query: ...}]
Instead of :
[ {ID: 123, query: ...},
{ID: 234, query: ...},
{ID: 456, query: ...}]
Upvotes: 0
Views: 55
Reputation: 84
The problem is that payloadObj
is defined outside of the map callback. Because of this, the same object is being mutated during the map callback and returned from the then
method called on the promise created in the map callback, so that the array passed to Promise.all
contains 3 promises which will all resolve to the same object, whose ID
property will be the last ID in the array (since this map callback is called last) and whose query
property will be the result of the last request that succeeds (probably, but not necessarily, the last request).
Upvotes: 3