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

查看:246
本文介绍了承诺可以在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){
    // ....
});

将同时收到 arg1 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.

不,只是第一个参数将被视为promise构造函数中的分辨率值。您可以使用复合值(如对象或数组)进行解析。

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.


我不关心任何特定的promises实现是如何实现的,我希望密切关注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期货可以可靠地使用并且库可以消耗。承诺实现现在用你的问题用 .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!";
});

蓝鸟。如果您想要此功能,一种解决方案是将其填充。

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

本机承诺轻松小提琴。或者在浏览器中使用现在(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天全站免登陆