Can promises have multiple arguments to onFulfilled?

JavascriptPromise

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

> 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', '!']);

Solution 2 - Javascript

You can use E6 destructuring:

Object destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled({arg1: value1, arg2: value2});
})

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

Array destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled([value1, value2]);
})

promise.then(([arg1, arg2]) => {
    // ....
});

Solution 3 - Javascript

The fulfillment value of a promise parallels the return value of a function and the rejection reason of a promise parallels the thrown exception of a function. Functions cannot return multiple values so promises must not have more than 1 fulfillment value.

Solution 4 - Javascript

As far as I can tell reading the ES6 Promise specification and the standard promise specification theres no clause preventing an implementation from handling this case - however its not implemented in the following libraries:

I assume the reason for them omiting multi arg resolves is to make changing order more succinct (i.e. as you can only return one value in a function it would make the control flow less intuitive) Example:

new Promise(function(resolve, reject) {
   return resolve(5, 4);
})
.then(function(x,y) {
   console.log(y);
   return x; //we can only return 1 value here so the next then will only have 1 argument
})
.then(function(x,y) {
    console.log(y);
});

Solution 5 - Javascript

Here is a CoffeeScript solution.

I was looking for the same solution and found seomething very intersting from this answer: https://stackoverflow.com/questions/17686612/rejecting-promises-with-multiple-arguments-like-http-in-angularjs

the answer of this guy Florian

promise = deferred.promise

promise.success = (fn) ->
  promise.then (data) ->
   fn(data.payload, data.status, {additional: 42})
  return promise

promise.error = (fn) ->
  promise.then null, (err) ->
    fn(err)
  return promise

return promise 

And to use it:

service.get().success (arg1, arg2, arg3) ->
    # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
    # => err

Solution 6 - Javascript

De-structuring Assignment in ES6 would help here.For Ex:

let [arg1, arg2] = new Promise((resolve, reject) => {
    resolve([argument1, argument2]);
});

Solution 7 - Javascript

Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled() method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled() method as long as the promise's value is the first argument.

>2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.

Solution 8 - Javascript

Great question, and great answer by Benjamin, Kris, et al - many thanks!

I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:

npm i -S promise-spread

Then in your code, do

require('promise-spread');

If you're using a library such as any-promise

var Promise = require('any-promise');
require('promise-spread')(Promise);

Maybe others find this useful, too!

Solution 9 - Javascript

To quote the article below, ""then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only."

I usually look to this page for any basic promise questions, let me know if I am wrong

http://www.html5rocks.com/en/tutorials/es6/promises/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbadunkView Question on Stackoverflow
Solution 1 - JavascriptBenjamin GruenbaumView Answer on Stackoverflow
Solution 2 - JavascriptWookiemView Answer on Stackoverflow
Solution 3 - JavascriptEsailijaView Answer on Stackoverflow
Solution 4 - JavascriptmegawacView Answer on Stackoverflow
Solution 5 - JavascriptVal EntinView Answer on Stackoverflow
Solution 6 - JavascriptRavi TejaView Answer on Stackoverflow
Solution 7 - JavascriptJazzepiView Answer on Stackoverflow
Solution 8 - JavascriptAndreasPizsaView Answer on Stackoverflow
Solution 9 - JavascriptMichael VoznesenskyView Answer on Stackoverflow