在.then函数中发送多个参数

har*_*rdy 3 javascript callback promise ecmascript-6 bluebird

在回调中,我们可以发送任意数量的参数.

同样,我想将多个参数传递给then函数,无论是在Bluebird promises还是本机JavaScript promise中.

像这样:

myPromise.then(a => {
    var b=122;
    // here I want to return multiple arguments
}).then((a,b,c) => {
    // do something with arguments
});
Run Code Online (Sandbox Code Playgroud)

Pat*_*und 7

您只需从then方法中返回一个对象即可.如果你在下一个使用解构,then就像将多个变量从一个传递then给下一个:

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

请注意,在第一个中then,我们使用快捷方式返回ab(它与使用相同{ a: a, b: b, c: 'foo' }).