Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple arguments in .then function

In callbacks we can send as many arguments as we want.

Likewise, I want to pass multiple arguments to a then function, either in Bluebird promises or native JavaScript promises.

Like this:

myPromise.then(a => {
    var b=122;
    // here I want to return multiple arguments
}).then((a,b,c) => {
    // do something with arguments
});
like image 1000
hardy Avatar asked Feb 04 '23 13:02

hardy


1 Answers

You can simply return an object from the then method. If you use destructuring in the next then, it will be like passing multiple variables from one then to the next:

myPromise.then(a => {
    var b = 122;
    return {
        a,
        b,
        c: 'foo'
    };
}).then(({ a, b, c }) => {
    console.log(a);
    console.log(b);
    console.log(c);    
});

Note that in the first then, we are using a shortcut for returning a and b (it's the same as using { a: a, b: b, c: 'foo' }).

like image 189
Patrick Hund Avatar answered Feb 07 '23 11:02

Patrick Hund