Navigation

Generator syntax

This syntax is the LazyPromise equivalent of async-await. It lets you take advantage of JavaScript control flow statements, and as with chained operators, you get auto-propagating cancellation. Just use generator functions instead of async functions, and yield* instead of await:

// Type inferred as LazyPromise<number>
const lazyPromise = fromGen(function* () {
  while (true) {
    // Type inferred as number | undefined
    const value = yield* new LazyPromise<number | undefined>(...);
    if (value !== undefined) {
      return value;
    }
  }
});

Everything behaves analogously to the async-await syntax, including try/catch/finally, using, and Node’s AsyncLocalStorage.

In particular, if you await promise, and promise rejects with error, it’s as if in place of await promise you had throw error. It works in exactly the same way when you have yield* lazyPromise and lazyPromise rejects.

If the whole flow is canceled while waiting at a yield*, it’s as if in place of that yield* you had return: catch blocks are skipped (looking at you AbortController), finally blocks run, and so do the disposers of using declarations.