0

One of the issues I have faced when crafting Promises for certain app context is that of wanting to delay any execution of the code inside the promise until later. This happens frequently when I have manager objects that maintain a collection of Promises for execution at a later time. To remedy this, I end up creating builder functions that are called by the manager objects at the time the Promise needs to be executed. This is tedious and leads to a fair amount of "boilerlate" code.

For example, here's one of my Promise builder functions:

this._buildPollingPromise = function(ethTransWaiter) {
    return new Promise(function(resolve, reject) {

        // Execute the function that builds a polling method promise.
        ethTransWaiter.confirmTransPromiseBuilder.buildPromise()
        .then(function(result) {
            ...
        })
        .then(function(ignoreResult) {
            resolve(ethTransWaiter.isConfirmed);
        })
        .catch(function(err)
        {
            // Reject the promise with the error received.
            reject(err);
        });
    });
}

I have to delay execution of the ethTransWaiter.confirmTransPromiseBuilder.buildPromise() method because if it executes at the time the Promise is created, it will fail because the conditions aren't in place yet for it to execute successfully.

Therefore, I am wondering if there is a built-in method, or an NPM package, that creates or helps create Promises that can be built in a dormant state, so that the code in the function that lives inside the Promise constructor does not execute until some later time (i.e. - at the precise time when you want it to execute) That would save me a lot of boilerplate coding.

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227
  • 1
    so, how do you know when it's *safe* to execute `ethTransWaiter.confirmTransPromiseBuilder.buildPromise` ... how/when do you call `_buildPollingPromise()`? – Jaromanda X Aug 15 '18 at 05:17
  • does [this pastebin](https://pastebin.com/S8037a9c) help at all? or better still [this pastebin](https://pastebin.com/pmNWtKVK) – Jaromanda X Aug 15 '18 at 05:29

1 Answers1

0

May be something like this?

function wait(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}

this._buildPollingPromise = function (ethTransWaiter) {

  var waitUntilLater = wait(3000);

  var buildPromise = new Promise(function (resolve, reject) {

    // Execute the function that builds a polling method promise.
    ethTransWaiter.confirmTransPromiseBuilder.buildPromise()
      .then(function (result) {
        //...
      })
      .then(function (ignoreResult) {
        resolve(ethTransWaiter.isConfirmed);
      })
      .catch(function (err) {
        // Reject the promise with the error received.
        reject(err);
      });
  });

  return Promise.all([waitUntilLater, buildPromise]).then(function (results) {
    return results;
  });

}
jeetaz
  • 691
  • 1
  • 6
  • 11