承诺可以有多个 onFulfilled 参数吗? [英] Can promises have multiple arguments to onFulfilled?

查看:26
本文介绍了承诺可以有多个 onFulfilled 参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循此处的规范,但我不确定它是否允许调用 onFulfilled带有多个参数.例如:

I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments. For example:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled('arg1', 'arg2');
})

这样我的代码:

promise.then(function(arg1, arg2){
    // ....
});

会同时收到 arg1arg2 吗?

would receive both arg1 and arg2?

我不关心任何具体的承诺实现是如何做到的,我希望密切关注 w3c 承诺的规范.

I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.

推荐答案

我正在遵循此处的规范,但不确定它是否允许使用多个参数调用 onFulfilled.

I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.

不,只有第一个参数将被视为承诺构造函数中的解析值.您可以使用复合值(如对象或数组)进行解析.

Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.

我不关心任何具体的承诺实现是如何做到的,我希望密切关注 w3c 承诺的规范.

I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.

那是我认为你错的地方.该规范被设计为最小化,并且是为 Promise 库之间的互操作而构建的.这个想法是拥有一个子集,例如 DOM 期货可以可靠地使用并且库可以使用.Promise 的实现现在用 .spread 做你要求的事.例如:

That's where I believe you're wrong. The specification is designed to be minimal and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with .spread for a while now. For example:

Promise.try(function(){
    return ["Hello","World","!"];
}).spread(function(a,b,c){
    console.log(a,b+c); // "Hello World!";
});

使用 Bluebird.如果您想要此功能,一种解决方案是对其进行 polyfill.

With Bluebird. One solution if you want this functionality is to polyfill it.

if (!Promise.prototype.spread) {
    Promise.prototype.spread = function (fn) {
        return this.then(function (args) {
            return Promise.all(args); // wait for all
        }).then(function(args){
         //this is always undefined in A+ complaint, but just in case
            return fn.apply(this, args); 
        });
    };
}

这让您可以:

Promise.resolve(null).then(function(){
    return ["Hello","World","!"]; 
}).spread(function(a,b,c){
    console.log(a,b+c);    
});

轻松实现原生承诺fiddle.或者使用现在(2018 年)在浏览器中司空见惯的传播:

With native promises at ease fiddle. Or use spread which is now (2018) commonplace in browsers:

Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
  console.log(a,b+c);    
});

或者使用等待:

let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);

这篇关于承诺可以有多个 onFulfilled 参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆