kuhaku kuhaku - 8 months ago 59
Javascript Question

Using Promise.all to return a value from a function

I'm trying to return an array that is being built with async calls, something like this:

I want

myArr
in the function that calls
foo()


function foo(){

let promiseArray = [];
let singlePromise;
let myArr = [];

for(let node of Nodes){

singlePromise = getSomePromise(node);
singlePromise.then(function(result){
myArr.push(bar(result));
});

promiseArray.push(singlePromise);
}

// return Promise.all(promiseArray)? but then I lose myArr
}


So how can I return
myArr
?

Answer Source

Rather than pushing to myArr, push promises that resolve to the values you need:

function foo() {
    const promiseArray = [];

    for (const node of Nodes) {
        const singlePromise =
            getSomePromise(node).then(function (result) {
                return bar(result);
            });

        promiseArray.push(singlePromise);
    }

    return Promise.all(promiseArray);
}

If you’re using a promise library like Bluebird (highly recommended), you can even do this:

const foo = () =>
    Promise.map(Nodes, node =>
        getSomePromise(node).then(bar)
    );

and if Nodes is an array:

const foo = () =>
    Promise.all(Nodes.map(getSomePromise)).map(bar);