deferred_promise

2024 Update: This module is unnecessary now that the Promise.withResolvers() function exists. Use that instead of this.

This library exports the DeferredPromise class which has the properties promise, resolve(value), and reject(reason). This is meant to be used to when you need to create an object that encapsulates a promise with the ability to fulfill it. The exposed promise is a normal promise object that can be passed around separately from the capability to fulfill it.

Don't use this unless you know what you're doing. The standard Promise constructor is usually superior because it limits the visibility of the resolve and reject capabilities in a closure. This is inconvenient in some situations.

Originally based on p-defer.

This library is available for Deno at https://deno.land/x/deferred_promise@v1.0.0/mod.ts, and is available for Node.js on npm as @macil/deferred-promise.

Usage

import { DeferredPromise } from "https://deno.land/x/deferred_promise@v1.0.0/mod.ts";
function delay(milliseconds: number) {
  const deferred = new DeferredPromise<string>();
  setTimeout(() => {
    deferred.resolve("🦄");
  }, milliseconds);
  return deferred.promise;
}
console.log(await delay(100));
//=> '🦄'

The above is just an example. Use std/async's delay if you need to delay a promise.