Convert Figma logo to code with AI

sindresorhus logopromise-fun

Promise packages, patterns, chat, and tutorials

4,712
131
4,712
1

Top Related Projects

20,444

:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

14,940

A promise library for JavaScript

2,578

Bare bones Promises/A+ implementation

3,615

A lightweight library that provides tools for organizing asynchronous code

28,153

Async utilities for node and the browser

16,717

:kangaroo: - PouchDB is a pocket-sized database.

Quick Overview

Promise-fun is a collection of useful Promise-based utilities and helpers for JavaScript. It provides a set of small, focused functions that simplify working with Promises, making asynchronous programming more manageable and expressive.

Pros

  • Lightweight and modular, allowing developers to use only the functions they need
  • Well-documented with clear examples for each utility
  • Improves readability and reduces boilerplate in Promise-based code
  • Actively maintained and regularly updated

Cons

  • Some utilities may have limited use cases or overlap with built-in JavaScript features
  • Requires understanding of Promises and asynchronous programming concepts
  • May introduce additional dependencies to a project
  • Learning curve for developers unfamiliar with functional programming patterns

Code Examples

  1. Using pTimeout to add a timeout to a Promise:
const pTimeout = require('p-timeout');

const fetchData = async () => {
  // Simulating a long-running operation
  await new Promise(resolve => setTimeout(resolve, 5000));
  return 'Data fetched';
};

const timeoutPromise = pTimeout(fetchData(), 3000, 'Operation timed out');

timeoutPromise.then(console.log).catch(console.error);
// Output: Operation timed out
  1. Using pMap to run Promise-returning functions concurrently:
const pMap = require('p-map');

const urls = ['https://example.com', 'https://example.org', 'https://example.net'];

const fetchUrl = async (url) => {
  const response = await fetch(url);
  return response.text();
};

pMap(urls, fetchUrl, { concurrency: 2 })
  .then(results => console.log('Fetched content:', results))
  .catch(console.error);
  1. Using pReduce to chain Promises sequentially:
const pReduce = require('p-reduce');

const numbers = [1, 2, 3, 4, 5];

const asyncSum = async (total, number) => {
  await new Promise(resolve => setTimeout(resolve, 100));
  return total + number;
};

pReduce(numbers, asyncSum, 0)
  .then(result => console.log('Sum:', result))
  .catch(console.error);
// Output: Sum: 15

Getting Started

To use promise-fun in your project, first install it via npm:

npm install p-map p-reduce p-timeout

Then, import and use the desired functions in your JavaScript code:

const pMap = require('p-map');
const pReduce = require('p-reduce');
const pTimeout = require('p-timeout');

// Use the imported functions as shown in the code examples above

Competitor Comparisons

20,444

:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

Pros of Bluebird

  • Extensive feature set with advanced Promise utilities
  • High performance, often faster than native Promises
  • Comprehensive error handling and debugging capabilities

Cons of Bluebird

  • Larger bundle size due to its extensive feature set
  • Steeper learning curve for developers new to Promises
  • Less focus on modern JavaScript practices and ES6+ compatibility

Code Comparison

Bluebird:

const Promise = require('bluebird');

Promise.map([1, 2, 3], (num) => {
  return Promise.delay(100).then(() => num * 2);
}).then(console.log);

Promise Fun:

import pMap from 'p-map';

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

pMap([1, 2, 3], async (num) => {
  await delay(100);
  return num * 2;
}).then(console.log);

Summary

Bluebird is a full-featured Promise library with excellent performance and extensive utilities. It's ideal for complex applications requiring advanced Promise handling. However, its large size and complexity may be overkill for simpler projects.

Promise Fun, on the other hand, offers a collection of smaller, focused modules for specific Promise-related tasks. It's more aligned with modern JavaScript practices and provides a modular approach, allowing developers to import only the functionality they need.

Choose Bluebird for comprehensive Promise handling in large-scale applications, or opt for Promise Fun when you need lightweight, specific Promise utilities in modern JavaScript projects.

14,940

A promise library for JavaScript

Pros of Q

  • More mature and battle-tested library with a longer history
  • Offers a wider range of utility functions for working with promises
  • Provides better support for older browsers and environments

Cons of Q

  • Larger file size and potentially slower performance
  • Less actively maintained compared to more modern alternatives
  • Steeper learning curve due to its extensive API

Code Comparison

Q:

Q.fcall(function () {
    return 10;
})
.then(function (result) {
    console.log(result);
});

promise-fun:

Promise.resolve(10)
    .then(result => {
        console.log(result);
    });

Summary

Q is a more established and feature-rich promise library, offering extensive functionality and broader compatibility. However, it comes with a larger footprint and may be overkill for simpler projects. promise-fun, on the other hand, is a collection of smaller, more focused promise-related utilities that align well with modern JavaScript practices and native Promise implementations.

While Q provides a comprehensive solution for complex asynchronous operations, promise-fun offers a more lightweight approach with individual utilities that can be cherry-picked as needed. The choice between the two depends on project requirements, performance considerations, and developer preferences.

2,578

Bare bones Promises/A+ implementation

Pros of then/promise

  • More comprehensive and feature-rich library
  • Provides advanced functionality like cancellation and progress tracking
  • Actively maintained with regular updates

Cons of then/promise

  • Larger footprint and potentially more complex to use
  • May include features not needed for simpler use cases
  • Steeper learning curve for beginners

Code Comparison

promise-fun:

import pMap from 'p-map';

const result = await pMap(items, async item => {
    const data = await fetchData(item);
    return processData(data);
}, {concurrency: 2});

then/promise:

import Promise from 'bluebird';

const result = await Promise.map(items, async item => {
    const data = await fetchData(item);
    return processData(data);
}, {concurrency: 2});

Summary

promise-fun is a collection of small, focused Promise-related packages, while then/promise (also known as Bluebird) is a full-featured Promise library. promise-fun offers simplicity and modularity, allowing developers to pick specific utilities as needed. then/promise provides a more comprehensive solution with additional features but may be overkill for simple projects. Both have similar syntax for common operations, as seen in the code comparison. The choice between them depends on project requirements and developer preferences.

3,615

A lightweight library that provides tools for organizing asynchronous code

Pros of rsvp.js

  • More comprehensive Promise implementation with additional features like RSVP.all(), RSVP.race(), and RSVP.hash()
  • Better suited for larger applications and complex asynchronous workflows
  • Actively maintained with regular updates and bug fixes

Cons of rsvp.js

  • Larger file size and potentially higher overhead compared to promise-fun
  • Steeper learning curve due to more extensive API and features
  • May be overkill for simple projects or when only basic Promise functionality is needed

Code Comparison

rsvp.js:

import RSVP from 'rsvp';

RSVP.all([promise1, promise2]).then(function(results) {
  // Handle resolved promises
}).catch(function(error) {
  // Handle errors
});

promise-fun:

import pAll from 'p-all';

pAll([
  () => promise1,
  () => promise2
]).then(results => {
  // Handle resolved promises
}).catch(error => {
  // Handle errors
});

Both libraries provide Promise-based functionality, but rsvp.js offers a more comprehensive set of features and is better suited for complex applications. promise-fun, on the other hand, focuses on providing smaller, more specialized utilities for working with Promises, making it ideal for simpler projects or when only specific Promise-related functionalities are needed.

28,153

Async utilities for node and the browser

Pros of async

  • More comprehensive and feature-rich library for handling asynchronous operations
  • Supports both callback-based and Promise-based APIs
  • Provides a wide range of utility functions for common async patterns

Cons of async

  • Larger package size and potential performance overhead
  • Steeper learning curve due to the extensive API
  • Some features may be redundant with modern JavaScript capabilities

Code Comparison

async:

async.waterfall([
  function(callback) {
    callback(null, 'one', 'two');
  },
  function(arg1, arg2, callback) {
    callback(null, 'three');
  },
  function(arg1, callback) {
    callback(null, 'done');
  }
], function (err, result) {
  console.log(result);
});

promise-fun:

const waterfall = require('p-waterfall');

waterfall([
  () => Promise.resolve(['one', 'two']),
  ([arg1, arg2]) => Promise.resolve('three'),
  (arg1) => Promise.resolve('done')
]).then(result => {
  console.log(result);
});

Both libraries provide utilities for handling asynchronous operations, but async offers a more extensive set of features and supports both callback and Promise-based approaches. promise-fun focuses on Promise-based utilities and provides a more lightweight solution. The choice between them depends on project requirements, preferred coding style, and the need for specific async patterns.

16,717

:kangaroo: - PouchDB is a pocket-sized database.

Pros of PouchDB

  • Full-featured database system with synchronization capabilities
  • Supports offline-first applications and real-time data syncing
  • Large and active community with extensive documentation

Cons of PouchDB

  • Larger codebase and more complex to implement
  • Steeper learning curve for beginners
  • May be overkill for simple promise-based operations

Code Comparison

PouchDB example:

const db = new PouchDB('mydb');
db.put({
  _id: 'mydoc',
  title: 'Hello PouchDB'
}).then(function (response) {
  console.log('Document created');
}).catch(function (err) {
  console.log(err);
});

promise-fun example:

const pMap = require('p-map');

const urls = [/* ... */];
const mapper = url => fetch(url).then(res => res.json());

pMap(urls, mapper, {concurrency: 2}).then(result => {
  console.log(result);
});

Summary

PouchDB is a comprehensive database solution with synchronization features, ideal for complex applications requiring offline support and real-time data syncing. promise-fun, on the other hand, is a collection of smaller, focused promise utility functions, better suited for simpler promise-based operations and easier to integrate into existing projects. While PouchDB offers more functionality, it comes with a steeper learning curve and may be excessive for basic promise handling tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

promise-fun

I intend to use this space to document my promise modules, useful promise patterns, and how to solve common problems. For now though, you can see all my promise modules below.

Contents

Packages

Not accepting additions, but happy to take requests.

  • pify: Promisify a callback-style function
  • delay: Delay a promise a specified amount of time
  • yoctodelay: Delay a promise a specified amount of time
  • p-map: Map over promises concurrently
  • p-all: Run promise-returning & async functions concurrently with optional limited concurrency
  • p-event: Promisify an event by waiting for it to be emitted
  • p-debounce: Debounce promise-returning & async functions
  • p-throttle: Throttle promise-returning & async functions
  • p-timeout: Timeout a promise after a specified amount of time
  • p-retry: Retry a promise-returning or async function
  • p-any: Wait for any promise to be fulfilled
  • p-some: Wait for a specified number of promises to be fulfilled
  • p-mutex: Ensure that only one operation accesses a particular resource at a time
  • p-locate: Get the first fulfilled promise that satisfies the provided testing function
  • p-limit: Run multiple promise-returning & async functions with limited concurrency
  • p-series: Run promise-returning & async functions in series
  • p-memoize: Memoize promise-returning & async functions
  • p-pipe: Compose promise-returning & async functions into a reusable pipeline
  • p-props: Like Promise.all() but for Map and Object
  • p-waterfall: Run promise-returning & async functions in series, each passing its result to the next
  • p-cancelable: Create a promise that can be canceled
  • p-progress: Create a promise that reports progress
  • p-reflect: Make a promise always fulfill with its actual fulfillment value or rejection reason
  • p-filter: Filter promises concurrently
  • p-reduce: Reduce a list of values using promises into a promise for a value
  • p-settle: Settle promises concurrently and get their fulfillment value or rejection reason with optional limited concurrency
  • p-map-series: Map over promises serially
  • p-each-series: Iterate over promises serially
  • p-times: Run promise-returning & async functions a specific number of times concurrently
  • p-lazy: Create a lazy promise that defers execution until .then() or .catch() is called
  • p-whilst: While a condition returns true, calls a function repeatedly, and then resolves the promise
  • p-do-whilst: Calls a function repeatedly while a condition returns true and then resolves the promise
  • p-forever: Run promise-returning & async functions repeatedly until you end it
  • p-wait-for: Wait for a condition to be true
  • p-min-delay: Delay a promise a minimum amount of time
  • p-try: Promise.try() ponyfill - Starts a promise chain
  • p-race: A better Promise.race()
  • p-immediate: Returns a promise resolved in the next event loop - think setImmediate()
  • p-time: Measure the time a promise takes to resolve
  • p-defer: Create a deferred promise
  • p-is-promise: Check if something is a promise
  • p-state: Inspect the state of a promise
  • p-queue: Promise queue with concurrency control
  • make-synchronous: Make an asynchronous function synchronous

.then/.catch-based packages

You should generally avoid using .then except in edge cases.

  • p-catch-if: Conditional promise catch handler
  • p-if: Conditional promise chains
  • p-tap: Tap into a promise chain without affecting its value or state
  • p-log: Log the value/error of a promise
  • p-break: Break out of a promise chain

FAQ

How can I run 100 async/promise-returning functions with only 5 running at once?

This is a good use-case for p-map. You might ask why you can't just specify an array of promises. Promises represent values of a computation and not the computation itself - they are eager. So by the time p-map starts reading the array, all the actions creating those promises have already started running. p-map works by executing a promise-returning function in a mapper function. This way the promises are created lazily and can be concurrency limited. Check out p-all instead if you're using different functions to get each promise.

import pMap from 'p-map';

const urls = [
	'https://sindresorhus.com',
	'https://avajs.dev',
	'https://github.com',
	…
];

console.log(urls.length);
//=> 100

const mapper = url => fetchStats(url); //=> Promise

const result = await pMap(urls, mapper, {concurrency: 5});

console.log(result);
//=> [{url: 'https://sindresorhus.com', stats: {…}}, …]

NPM DownloadsLast 30 Days