Deferred Promise

Found myself in a situation where I wanted to execute a process and then check back on it later to be sure it had completed.

class MyClass {
  constructor() {
    this.readyPromise = new Promise(
      resolve => (this.readyResolve = resolve)
    );
  }

  async executeProcesses() {
    await // ...executing processes...
    this.readyResolve();
  }

  ready() { return this.readyPromise }
}

Assigning a reference to the resolve function (this.readyResolve in constructor) dissociates it from the promise so it can be resolved at any time by any other method.

Any external script simply has to get a reference to the original promise that created the resolve:

await myClass.ready();

Leave a Reply

Your email address will not be published. Required fields are marked *