A Promise-compatible abstraction that defers resolving/rejecting promises to another closure.

Overview

Deferred Promise

The DeferredPromise class is a Promise-compatible abstraction that defers resolving/rejecting promises to another closure. This class is primarily useful when one part of your system establishes as promise but another part of your system fulfills it.

This class is conceptually inspired by the createDeferredPromise() internal utility in Node.js. Unlike the Node.js implementation, however, DeferredProimse extends a native Promise, allowing the consumer to handle deferred promises like regular promises (no .promise instance nesting).

Getting started

npm install @open-draft/deferred-promise

Documentation

Class: DeferredPromise

new DefferedPromise()

Creates a new instance of a deferred promise.

import { DeferredPromise } from '@open-draft/deferred-promise'

const promise = new DeferredPromise()

Unlike the regular Promise, a deferred promise does not accept the callback function. Instead, you should use .resolve() and .reject() to resolve and reject the promise respectively.

A deferred promise is fully compatible with the native Promise, which means you can pass it to the consumers that await a regular Promise as well.

deferredPromise.state

  • <"pending" | "resolved" | "rejected"> Default: "pending"
const promise = new DeferredPromise()
console.log(promise.state) // "pending"

promise.resolve()
console.log(promise.state) // "resolved"

deferredPromise.result

Returns the value that has resolved the promise. If no value has been provided to the .resolve() call, undefined is returned instead.

const promise = new DeferredPromise()
promise.resolve('John')

console.log(promise.result) // "John"

deferredPromise.rejectionReason

Returns the reason that has rejected the promise. If no reason has been provided to the .reject() call, undefined is returned instead.

const promise = new DeferredPromise()
promise.reject(new Error('Internal Server Error'))

console.log(promise.rejectionReason) // Error

deferredPromise.resolve()

Resolves the deferred promise with a given value.

function startServer() {
  const serverReady = new DeferredPromise()

  new http.Server().listen(() => {
    // Resolve the deferred promise with the server address
    // once the server is ready.
    serverReady.resolve('http://localhost:8080')
  })

  // Return the deferred promise to the consumer.
  return serverReady
}

startServer().then((address) => {
  console.log('Server is running at "%s"', address)
})

deferredPromise.reject()

Rejects the deferred promise with a given reason.

function createBroadcast() {
  const runtimePromise = new DeferredPromise()

  receiver.on('error', (error) => {
    // Reject the deferred promise in response
    // to the incoming "error" event.
    runtimePromise.reject(error)
  })

  // This deferred promise will be pending forever
  // unless the broadcast channel receives the
  // "error" event that rejects it.
  return runtimePromise
}
You might also like...

Ajax library with XHR2, promises and request limit

qwest 4.5.0 ⚠ I finally decided to archive this repository. ⚠ At first, I developed Qwest because at the time other libraries were lacking of a proper

Sep 14, 2022

A request library that returns promises, inspired by request

then-request A request library that returns promises and supports both browsers and node.js Installation npm install then-request Usage request(metho

Nov 29, 2022

A polyfill for ES6-style Promises

ES6-Promise (subset of rsvp.js) This is a polyfill of the ES6 Promise. The implementation is a subset of rsvp.js extracted by @jakearchibald, if you'r

Dec 28, 2022

Remembering promises that were made!

remember-promise A simple utility to remember promises that were made! It is greatly inspired by the p-memoize utility but with additional built-in fe

Dec 15, 2022

Init a target by promise only once.

once-init 🗼 Let Promise Function Executed Only Once. The Promise will be executed when the attribute target is called for the first time, and the Pro

Dec 26, 2022

Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill).

@sanity/client Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill). Requirements Sanity Clien

Nov 29, 2022

Debounce promise-returning & async functions.

perfect-debounce An improved debounce function with Promise support. Well tested debounce implementation Native Promise support Avoid duplicate calls

Jan 2, 2023

Promise-based utility to control modal states in React

Promise-based utility to control modal states in React

Promise-based utility to control modal states in React Zero-dependency library that easily integrates with your existing UI components and allows you

Dec 5, 2022

A simple Node.js package that helps you not to look up JavaScript promise syntax every time you use it.

A simple Node.js package that helps you not to look up JavaScript promise syntax every time you use it.

A simple Node.js package that helps you not to look up JavaScript promise syntax every time you use it. Simple: Provides abstraction of the promise sy

Oct 8, 2022
Comments
  • feat: improve Promise-compliance

    feat: improve Promise-compliance

    FYI, got both the subclassed version and the standalone one (doesn't rely on Promise at all) to work! Both pass your tests and the A+ test suite and I managed to get the types working, too :)

    You can switch between the implementations by adjusting the commented exports at the bottom in DeferredPromise.ts, and run the tests with npm test && npm run test-aplus.

    Give them a try and feel free to use them or to borrow stuff for your impl :)

    opened by jonaskuske 3
  • feat: add deferred executor, support chaining

    feat: add deferred executor, support chaining

    BREAKING CHANGE: Deferred promises are now implemented via the deferred executor function. There are no changes to the existing public API.

    Changes

    • Supports Promise chaining.
    • Adds createDeferredExecutor to use this library with any Promise.
    • Improves type annotations in regard to what the deferred promise expects as the input and what is the promise's output:
    const p = new DeferredPromise<number>()
      .then(() => 'hello')
    
    // The input must be "number".
    p.resolve(5)
    
    // the output is "string"
    // (the result of the "then" chain)
    await p // "hello"
    
    • Deprecated: Removes DeferredPromise.result. Access the result by awaiting the promise instead.
    • Deprecated: The resolved promise state is replaced by fulfilled, which is the correct promise state representation per specification.

    Roadmap

    • [x] Document the deferred executor with more detail and then mention it in the deferred promise class documentation. That's exactly their relationship.
    • [x] Support promises returned from .then/.catch.
    opened by kettanaito 1
  • feat: support

    feat: support ".finally()"

    • Adds support for .finally() method on the deferred promise.
    • Fixes an issue when catching an exception would still treat the deferred promise as unhandled (re-assign this.promise in the then/catch/finally methods).
    • Adds JSDoc descriptions for the .then(), .catch(), and .finally() methods.
    opened by kettanaito 1
Releases(v2.1.0)
  • v2.1.0(Dec 7, 2022)

  • v2.0.0(Nov 24, 2022)

    v2.0.0 (2022-11-24)

    ⚠️ BREAKING CHANGES

    • add deferred executor, support chaining (#4) (1fe382e81d5836769a4b5b2be78a28cffe0967f9)

    Deferred promises are now implemented via the deferred executor function. There are no changes to the existing public API.

    Changes

    • Supports Promise chaining.
    • Adds createDeferredExecutor to use this library with any Promise.
    • Improves type annotations in regard to what the deferred promise expects as the input and what is the promise's output:
    const p = new DeferredPromise<number>()
      .then(() => 'hello')
    
    // The input must be "number".
    p.resolve(5)
    
    // the output is "string"
    // (the result of the "then" chain)
    await p // "hello"
    
    • Deprecated: Removes DeferredPromise.result. Access the result by awaiting the promise instead.
    • Deprecated: The resolved promise state is replaced by fulfilled, which is the correct promise state representation per specification.
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Oct 20, 2022)

  • v1.2.1(Oct 20, 2022)

  • v1.2.0(Oct 20, 2022)

  • v1.1.1(Sep 26, 2022)

  • v1.1.0(Sep 26, 2022)

  • v1.0.0(Sep 12, 2022)

    v1.0.0 (2022-09-12)

    ⚠️ BREAKING CHANGES

    • add initial DeferredPromise implementation (512313d55168022b831a5cdba95dc03cf087c1eb)

    This is a 1.0 release.

    Source code(tar.gz)
    Source code(zip)
Owner
Open Draft
Libraries and utilities for Node.js ecosystem
Open Draft
Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Lily Scott 3 Feb 28, 2022
Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise.

Tape With Promises Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise. Install npm install --save-dev @smal

Small Technology Foundation 3 Mar 21, 2022
Run async code one after another by scheduling promises.

promise-scheduler Run async code in a synchronous order by scheduling promises, with the possibility to cancel pending or active tasks. Optimized for

Matthias 2 Dec 17, 2021
CodeTogether is a platform that aims to bring all the developers and coders together to appreciate collaborative coding by resolving issues faced by programmers on normal IDEs/platforms

CodeTogether is a platform that aims to bring all the developers and coders together to appreciate collaborative coding by resolving issues faced by programmers on normal IDEs/platforms. It allows developers to communicate with their fellow developers or collaborators through online voice call and realtime chat. Besides, the whiteboard makes the framing of an algorithm easier by helping programmers working collaboratively to discuss and plan their approach together

Shayan Debroy 5 Jan 20, 2022
A webpack plugin to enforce case-sensitive paths when resolving module

@umijs/case-sensitive-paths-webpack-plugin A webpack plugin to enforce case-sensitive paths when resolving module, similar to the well-known case-sens

UmiJS 13 Jul 25, 2022
Merge multiple Prisma schema files, model inheritance, resolving name conflicts and timings reports, all in a simple tool.

Prisma Util What is Prisma Util? • How to use? • The configuration file • Support What is Prisma Util? Prisma Util is an easy to use tool that merges

David Hancu 21 Dec 28, 2022
An abstraction layer on top of @replit/crosis that makes Repl connection management and operations so easy, a Furret could do it! 🎉

Crosis4Furrets An abstraction layer on top of @replit/crosis that makes Repl connection management and operations so easy, a Furret could do it! ?? In

Ray 18 Dec 29, 2022
A lightweight abstraction between Svelte stores and Chrome extension storage.

Svelte Chrome Storage A lightweight abstraction between Svelte stores and Chrome extension storage. This library makes data synchronization of backgro

Shaun Wild 10 Nov 15, 2022
Resolve parallel promises in key-value pairs whilst maintaining type information

async-kv Resolves promises in key-value pairs maintaining type information. Prerequisites NodeJS 12 or later Installation npm i async-kv yarn add asyn

Tony Tamplin 4 Feb 17, 2022
🐶 Learn JS Promises, with your friend 👑 Princess!

?? Learn JS Promises, with your friend ?? Princess!

Baylee Schmeisser 10 Jun 9, 2022