Skip to content Skip to sidebar Skip to footer

Returning Function And Invoking With Promise.all

I am expecting result: here is the value: a but I instead get result: [ [Function] ].

Solution 1:

getMyFunction returns a function that returns a promise, so you need to call myFunction to get the promise:

const myFunction = getMyFunction('a');
Promise.all([
    myFunction(), // <-- note here
]).then((result) => {
    console.log('result: ', result);
});

Solution 2:

getMyFunction does what the name suggests: It gets you a function. It doesn't call it. Promise.all expects a promise. You'd have to call that function to get the promise.

You probably want it to be getMyPromise and have it actually return the promise, rather than a function that will, since the nature of Promise.all is that things are running in parallel (I assume you'll have more tha one function; otherwise, no point to Promise.all at all):

functiongetMyPromise(data) {
    returnnewPromise((resolve, reject) => {
        resolve('here is the value: ' + data);
    });
}

Promise.all([
    getMyPromise('a'),
    getMyPromise('b'),
    getMyPromise('c')
]).then((result) => {
    console.log('result: ', result);
});

Post a Comment for "Returning Function And Invoking With Promise.all"