Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@meaku
Last active August 28, 2015 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meaku/38b64e61263e1202c47b to your computer and use it in GitHub Desktop.
Save meaku/38b64e61263e1202c47b to your computer and use it in GitHub Desktop.

Passing values

Problem: Promises resolve only with a single value. If you want to pass on the result of PromiseCall1 to PromiseCall2, you have different options:

Nesting

You can nest a .then() for Promise Call 2 and return both value from the scope.

  • Nesting makes it harder to read and should be avoided
delay("A")
    .then(function (A) {
    
        return delay("B")
            //nested then with access to A and B
            .then(function (B) {
                return [A, B];
            });
    })
    .then(function (result) {
        console.log(result[0]); //= A
        console.log(result[1]); //= B
    });

Promise.all

You could use Promise.all to resolve the value A and the Promise call for B.

  • No more nesting
  • Promise.all() is harder to grasp then return [A, B]
delay("A")
    .then(function (A) {
        return Promise.all([A, delay("B")]);
    })
    .then(function (result) {
        console.log(result[0]); //= A
        console.log(result[1]); //= B
    });

Keeping state

You could store the state within the function, so every nested then can access it.

  • keeping state in a scope object makes the function harder to grasp
  • might be a valid soltion for long promise chains
function ABC() {

    var state = {};

    delay("A")
        .then(function (A) {
            
            //store A in state for the next .then()
            state.A = A;
            return delay("B");
        })
        .then(function (B) {
            console.log(state.A); //= A
            console.log(B); //= B
        });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment