Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  141] [ 6]  / answers: 1 / hits: 123757  / 10 Years ago, mon, march 31, 2014, 12:00:00

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


such that my code:



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


would receive both arg1 and arg2?



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


More From » promise

 Answers
62

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.




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




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


This lets you do:



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


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


Or with await:



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

[#71692] Friday, March 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
abagail

Total Points: 528
Total Questions: 109
Total Answers: 101

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
abagail questions
Tue, Aug 16, 22, 00:00, 2 Years ago
Mon, Sep 27, 21, 00:00, 3 Years ago
Sun, May 30, 21, 00:00, 3 Years ago
Sun, Jan 3, 21, 00:00, 3 Years ago
;