Skip to content Skip to sidebar Skip to footer

Wait For Nested Js Promise To Finish Before Resolving Original Promise

I am new to Promises and I'm having a little trouble with the concept of waiting for a nested promise to finish all executions before resolving the original promise. Original Code

Solution 1:

First, avoid the Promise/Deferred antipattern. Rarely you need to create your own promises, usually you have some function that returns a Promise; use that.

Second, for the outer Promise to wait for a nesed PRomise, you need to return that nested Promise to the outer Promise. Returning a Promise inside of then() will make the resulting Promise to resolve to the value of the Promise you retuned inside.

And last, something like .then(value => value) or .then(value => Promise.resolve(someFunction(value)))is pointless. Your wrapper around anotherFunction basically just passed through the argument and returned the result.

So, your Pseudocode should look something like this:

functiongetSomething(text) {
  return getElse(text).then(function (items) {
    if (items.length !== 0) {
      /* Stuff here */return getElseElse(box).then(function (moreItems) {
        /* Stuff here */returnarray;
      }).then(anotherFunction);
    } else {
      returnnull;
    }
  });
}

Solution 2:

The basic trick is to make sure all of your resolve() calls are inside of the nested promises' then() methods.

Something along the lines of:

functiongetSomething(text) {
    returnnew Promise(function (resolve, reject) {
        getElse(text).then(function (items) {
            if (items.length !== 0) {

                /* Stuff here */

                getElseElse(box).then(function (moreItems) {

                    /* Stuff here */returnarray;
                }.then(function (array) {
                    var promise = new Promise(function (resolve, reject) {
                        result = anotherFunction(array); <-- Spot 1
                    });
                    promise.then(function () { });

                    resolve(result); <--- Spot 2
                });    
            }
            else {
                resolve(null);
            }
        });
    });
};

If it needs to be nested in the promise.then() above, just stick it in there instead.

Also note that you don't need to return your resolves. Just call them.

Post a Comment for "Wait For Nested Js Promise To Finish Before Resolving Original Promise"