I am encountering an issue with a function that is returning an Array filled with undefined
values.
Below is the code segment in question:
classMethods.getQueries = function(models, dbId, dateStart, dateEnd) {
return new Promise(function(resolve, reject) {
// Retrieving database.
.then(extractQueries, reject)
.then(sortQueries, reject)
.then(onlyTen, reject)
.then(addText, reject)
.then(function(queries) {
console.log("getQueries completed", queries); // Array consisting of 10× undefined!
resolve(queries);
}, reject);
// Additional functions go here.
});
};
Everything runs smoothly until the addText
function is called:
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 results in the following output:
"getQueries completed" [ undefined ×10 ]
10×
[query from database]
{ queryId: "…", text: "…" }
The reason behind the promise being returned before the loop completes is unclear to me.