Promise.all Invoking Array Variable Full Of Functions
Solution 1:
You're passing an array of functions into Promise.all
, but it expects an array of promises.
Unless there is a reason you want to produce a bunch of functions that you have to then execute, it would be simpler to just produce promises instead:
function getMyPromise(data) {
return new Promise((resolve, reject) => {
resolve('here is the value:' + data);
});
}
Then this should work fine:
const stuffArray = whatToGet.map(getMyPromise);
Promise.all(stuffArray).then((result) => {
console.log('result: ', result);
});
Side note/protip: don't use new Promise
if you want to create a promise for a specific value. Just use Promise.resolve
:
function getMyPromise(data) {
return Promise.resolve('here is the value:' + data);
}
Solution 2:
Well if you expect this result then make sure that you are calling the promises:
const stuffArray = whatToGet.map(thing => getMyFunction(thing)());
Notice: getMyFunction(thing)()
where we are actually calling the returned anonymous function from getMyFunction
in order to reach out to the actual promise.
Alternatively if you want to use your current code then make sure that getMyFunction
returns a promise and not a function that returns a promise:
function getMyFunction(data) {
return new Promise((resolve, reject) => {
resolve('here is the value:' + data);
});
}
Solution 3:
Instead of:
Promise.all(stuffArray).then((result) => {
console.log('result: ', result);
});
Use:
Promise.all(stuffArray.map(func => func())).then((result) => {
console.log('result: ', result);
});
Post a Comment for "Promise.all Invoking Array Variable Full Of Functions"