Search code examples
javascriptcallbackecmascript-6promisebluebird

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
});

Solution

  • 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' }).