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.
all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.
If a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value.
all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error. Some libraries have something called Promise.
To use Promise. all() with TypeScript, we can use it as we do with JavaScript. const [foo, bar] = await Promise. all([fooPromise, barPromise]);
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);
});
}));
};
So here the solution of my problem:
function addText(queries) {
return Promise.all(queries.map(function(query) {
return new Promise(function(resolve, reject) {
models.queries.findById(query.queryId, { raw: true, attributes: ['query'] })
.then(function(queryFetched) {
query.text = queryFetched.query;
resolve(query);
}, reject);
});
}));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With