Himmators
Himmators

Reputation: 15026

Returning a promise

I wish to return a promise that is dependent on other asynchronous requests. This is the best I came up with:

return Promise.all([user, name, fbprofile, phone])
    .then((results) => {
    return results[0].addUserAttributes([results[1], results[2], results[3]])
        .then((response) => response);
    });

It's three nested returns and all variables have been packed into an array. This makes the code hard to understand in my opinion.

Is there some way to achieve the same result without nesting functions?

Upvotes: 0

Views: 68

Answers (2)

Nix
Nix

Reputation: 58622

I don't know how to make this ecma6 but you should be able to just do the following:

//function to call once all are resolved.
function afterAllResolved(results){
   return results[0]
              .addUserAttributes(
                  [results[1], 
                   results[2],    
                   results[3])
}

return Promise
         .all([user, name, fbprofile, phone])
         .then(afterAllResolved);

This will call your function and return the result from the results[0].add as the resolved item.

Upvotes: 1

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

There is no "better" way, but a bit of deconstructing may add a bit of clarity. Also, the last then is useless.

return Promise.all([user, name, fbprofile, phone])
    .then(([userResult, ...otherResults]) =>
        userResult.addUserAttributes(otherResults)
    });

Upvotes: 3

Related Questions