Promise.all is returning an array of undefined
13,166
It's because you're not returning any promise in your map's callback:
function addText(queries) {
return Promise.all(queries.map(function(query) {
// add return here or the map returns an array of undefined
return models.queries
.findById(query.queryId, {
raw: true,
attributes: ['query']
})
.then(function(queryFetched) {
query.text = queryFetched.query;
console.log(query);
return Promise.resolve(query);
}, function(error) {
return Promise.reject(error);
});
}));
};
Author by
Guillaume Robbe
Updated on June 13, 2022Comments
-
Guillaume Robbe almost 2 years
I am having trouble with function returning an array of undefined.
Here is code:
classMethods.getQueries = function(models, dbId, dateStart, dateEnd) { return new Promise(function(resolve, reject) { /* Fetch database .... */ .then(extractQueries, reject) .then(sortQueries, reject) .then(onlyTen, reject) .then(addText, reject) .then(function(queries) { console.log('getQueries finished', queries) ; //array of 10 undefined! resolve(queries); }, reject); /* Functions here .... */ }); };
Everything is fine until the addText function:
function addText(queries) { return Promise.all(queries.map(function(query) { models.queries.findById(query.queryId, { raw: true, attributes: ['query'] }) .then(function(queryFetched) { query.text = queryFetched.query; console.log(query); return Promise.resolve(query); }, function(error) { return Promise.reject(error); }); })); };
This is giving me an oupout like:
getQueries finished [undedfined 10x] 10x [query database] {queryId: ***, text: ********}
I have no idea why the promise is return while the loop is not finished.
Thanks for the help.
-
Guillaume Robbe over 8 yearsAh yes I confused the return of the map and the then callback. Thanks for the help!