npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

promise-mixin

v1.0.7

Published

A handy and flexible helper that lets you augment the promise object in a safe and reliable way

Downloads

1

Readme

Installation

npm i promise-mixin

Usage

Note that the following use-case is simplified and regular class ExtendedPromise extends Promise is recommended instead.

import { createPromiseMixin } from 'promise-mixin'
const typicalPromise = new Promise((resolve) => resolve(true))
const externalPromise = createPromiseMixin(typicalPromise, {
  killed: () => true,
})

console.log(externalPromise.killed()) // outputs true

Motivation

This package was created to solve the cases when you need support for ad-hoc extension of javascript objects and/or you don't have control over the resulting promise object. For example when the resulting promise is returned from a library.

In all other cases I recommend using the tranditional inherintance via the extends keyword.

Use-cases

Case 1: Fixing an augmented promise from an external library

Problem:

const childProcessPromise = execa('ls') // Returns augmented Promise object
console.log(childProcessPromise)

/*
ChildProcess {
  connected: false,
  signalCode: null,
  exitCode: null,
  killed: false,
 ...
  // note that it also got native Promise prototype methods
  then: [Function],
  catch: [Function],
  finally: [Function],
}
*/
const newChildPromise = childProcessPromise.then((result) => undefined) // do something
console.log(newChildPromise) // all the augmented methods connected, signalCode, etc. are lost
/*
Promise {
  then: [Function],
  catch: [Function],
  finally: [Function],
}
*/

Solution:

import { createPromiseMixin } from 'promise-mixin'
const childProcessPromise = execa('ls')
const properMixinPromise = createPromiseMixin(
  childProcessPromise.then(),
  object,
) // fixing the protype chain

const newChildPromise = childProcessPromise.then((result) => undefined) // do something and return new promise
console.log(newChildPromise) // all the augmented methods connected, signalCode, etc. are preserved
/*
ChildProcess {
  connected: false,
  signalCode: null,
  exitCode: null,
  killed: false,
 ...
  then: [Function],
  catch: [Function],
  finally: [Function],
}
*/
Case 2: Adding an ad-hoc method or property onto a promise object (and preserving it )
import { createPromiseMixin } from 'promise-mixin'
const typicalPromise = promiseFromAnExternalLibrary() //
const externalPromise = createPromiseMixin(typicalPromise, {
  onAbortListener: (listener: () => void) => undefined, // logic,
})

externalPromise.onAbortListener(() => showNotification())

// promise chaining works as well

externalPromise
  .then()
  /*a new promise is created, the mixin methods are still there */
  .onAbortListener(() => showNotification())
externalPromise
  .catch()
  /*a new promise is created, the mixin methods are still there*/
  .onAbortListener(() => showNotification())
externalPromise
  .finally()
  /*a new promise is created, the mixin methods are still there*/
  .onAbortListener(() => showNotification())
Case 3: Adding the abort method right on the promise object
function runFetch(): Promise<string> & { abort: () => void } {
  const controller = new AbortController()
  const signal = controller.signal
  return createPromiseMixin(
    fetch(url, { signal })
      .then((response) => {
        console.log('Download complete', response)
      })
      .catch((err) => {
        console.error(`Download error: ${err.message}`)
      }),
    { abort: () => controller.abort() },
  )
}

const fetchPromise = runFetch()

eventManager.on('immediate-exit', () => fetchPromise.abort())

await fetchPromise

Warning: Do not use ASYNC when returning the augmented promise

Right:

function runFetch() {
  return createPromiseMixin(
    ...
  )
}

console.log(runFetch()) // Promise<string> & { abort: () => void }

Wrong:

async function runFetch() {
  return createPromiseMixin(
    ...
  )
}

console.log(runFetch()) // Promise<string>

When using async, the the augmented Promises will be wrapped with the regular Promise object.