我在这里遵循规范,我不确定它是否允许使用多个参数调用 onFulfilled。
不,只有第一个参数将被视为Promise构造函数中的解析值。您可以使用复合值(如对象或数组)进行解析。
我不关心任何特定的Promise实现是如何做到的,我希望密切关注 w3c 的Promise规范。
这就是我相信你错的地方。该规范被设计为最小的,并且是为 Promise 库之间的互操作而构建的。这个想法是拥有一个子集,例如 DOM 期货可以可靠地使用并且库可以使用。Promise 实现现在可以满足您的要求.spread
。例如:
Promise.try(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c); // "Hello World!";
});
与蓝鸟。如果您想要此功能,一种解决方案是对其进行 polyfill。
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);
});
用原生的Promise放心地拨弄。或者使用现在(2018)在浏览器中司空见惯的传播:
Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
console.log(a,b+c);
});
或等待:
let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);