Created
May 19, 2019 22:42
-
-
Save pr1sm/c7c10d14cd96bb66663a3fc816b39c1e to your computer and use it in GitHub Desktop.
Completer class that allows deferring Promise resolution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Completer | |
// | |
// Wrap a Promise and expose `resolve'`/`reject` safely to allow | |
// resolution/rejection to be determined after promise is created. | |
// | |
// Use: | |
// ```js | |
// const completer = new Completer(); | |
// | |
// async function step1() { | |
// console.log('doing async work...'); | |
// // do async work... | |
// // after async work, set the completer | |
// completer.complete(); | |
// console.log('done with step1'); | |
// } | |
// | |
// async function step2() { | |
// console.log('also doing async work...'); | |
// // do async work here... | |
// // Wait for completer since we need step1 to finish first | |
// await completer.value; | |
// console.log('continuing with more async work...'); | |
// // do more async work... | |
// console.log('done with step2'); | |
// } | |
// | |
// async function run() { | |
// // Run both promises concurrently... | |
// await Promises.all([step1(), step2()]); | |
// // Order shouldn't matter, step2 should always wait for step1 | |
// // await Promises.all([step2(), step1()]); | |
// } | |
// | |
// run(); | |
// ``` | |
class Completer { | |
constructor() { | |
this.value = new Promise((resolve, reject) => { | |
this._resolve = resolve; | |
this._reject = reject; | |
}); | |
} | |
complete(value) { | |
if (this._resolve) { | |
this._resolve(value); | |
this._resolve = null; | |
this._reject = null; | |
} | |
} | |
error(err) { | |
if (this._reject) { | |
this._reject(err); | |
this._resolve = null; | |
this._reject = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment