Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables through promise chain

I need to pass a variable through a promise .then chain. I can't find a way to work it out. I'm quite new to this so bear with me!

return foo.bar(baz)
         .then((firstResult) => {
           let message = firstResult;
         })
         .then(() => foo.bar(qux)
           .then((secondResult) => {
             message =+ secondResult;
             console.log(message);
           })
         )

What's the correct way of doing this please?

like image 658
Nathan Liu Avatar asked Dec 24 '22 06:12

Nathan Liu


1 Answers

Don't use a promise chain for this.

You are making two, independent calls to foo.bar() and neither of them depend on the results of the other.

Make them independently, and get all their data at the end with Promise.all.

var promises = [
    foo.bar(baz),
    foo.bar(qux)
];
Promise.all(promises).then( results => {
    let message = results[0] + results[1];
    console.log(message);
});
like image 117
Quentin Avatar answered Dec 25 '22 22:12

Quentin