Convert Figma logo to code with AI

then logopromise

Bare bones Promises/A+ implementation

2,577
314
2,577
20

Top Related Projects

20,444

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

14,940

A promise library for JavaScript

28,153

Async utilities for node and the browser

Lightweight ES6 Promise polyfill for the browser and node. A+ Compliant

A polyfill for ES6-style Promises

Quick Overview

Then/Promise is a lightweight JavaScript Promise library that provides a simple and efficient implementation of Promises. It aims to be fully compliant with the Promises/A+ specification while offering additional utility methods for enhanced functionality.

Pros

  • Lightweight and fast implementation
  • Fully compliant with Promises/A+ specification
  • Includes additional utility methods beyond the standard Promise API
  • Well-documented and easy to use

Cons

  • Less popular compared to native Promises or other well-established libraries
  • May lack some advanced features found in more comprehensive Promise libraries
  • Limited community support and ecosystem compared to native Promises
  • Potential learning curve for developers already familiar with native Promises

Code Examples

  1. Creating and resolving a Promise:
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

promise.then(result => console.log(result));
  1. Chaining Promises:
Promise.resolve(1)
  .then(value => value * 2)
  .then(value => value + 3)
  .then(result => console.log(result)); // Output: 5
  1. Using Promise.all:
const promises = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
];

Promise.all(promises)
  .then(results => console.log(results)); // Output: [1, 2, 3]

Getting Started

To use Then/Promise in your project, follow these steps:

  1. Install the library using npm:
npm install then/promise
  1. Import and use the Promise implementation in your JavaScript code:
const Promise = require('then/promise');

const myPromise = new Promise((resolve, reject) => {
  // Your asynchronous code here
  setTimeout(() => {
    resolve('Done!');
  }, 1000);
});

myPromise.then(result => console.log(result));

Now you can use the Then/Promise library in your project, taking advantage of its Promises/A+ compliant implementation and additional utility methods.

Competitor Comparisons

20,444

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

Pros of Bluebird

  • Significantly faster performance in most scenarios
  • More extensive feature set, including advanced utilities like Promise.map and Promise.reduce
  • Better error handling with long stack traces and detailed debugging information

Cons of Bluebird

  • Larger library size, which may impact load times in browser environments
  • Steeper learning curve due to the extensive API and additional features
  • Less adherence to the native Promise specification, potentially leading to compatibility issues

Code Comparison

Bluebird:

Promise.map(items, item => processItem(item))
  .then(results => console.log(results))
  .catch(error => console.error(error));

Promise:

Promise.all(items.map(item => processItem(item)))
  .then(results => console.log(results))
  .catch(error => console.error(error));

The code comparison shows how Bluebird provides a more concise Promise.map method, while Promise relies on the combination of Promise.all and Array.map. Bluebird's approach is often more readable and efficient for processing arrays of promises.

Both libraries offer similar core functionality, but Bluebird extends beyond the basic Promise implementation with additional utilities and performance optimizations. Promise, on the other hand, stays closer to the native Promise specification, which can be beneficial for projects prioritizing simplicity and standards compliance.

14,940

A promise library for JavaScript

Pros of Q

  • More comprehensive feature set, including advanced error handling and progress tracking
  • Better support for older browsers and environments
  • Extensive documentation and community support

Cons of Q

  • Larger library size, which may impact load times and performance
  • Steeper learning curve due to more complex API
  • Less active development and maintenance in recent years

Code Comparison

Q:

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

Promise:

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

Summary

Q offers a more feature-rich and battle-tested solution, particularly for projects requiring broad browser support or complex asynchronous operations. However, Promise provides a lighter-weight and more modern alternative that aligns closely with the native Promise API. The choice between the two largely depends on specific project requirements, with Promise being generally preferred for newer applications due to its simplicity and native support in modern environments.

28,153

Async utilities for node and the browser

Pros of async

  • Provides a comprehensive collection of async utility functions
  • Supports both callbacks and Promises, offering flexibility
  • Has a larger ecosystem and community support

Cons of async

  • Larger package size due to extensive functionality
  • Steeper learning curve for beginners due to numerous methods
  • May be overkill for simple async operations

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:

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

The async library offers more built-in utilities for complex async operations, while promise focuses on providing a streamlined Promise implementation. async is better suited for projects with diverse async needs, while promise is ideal for simpler Promise-based workflows.

Lightweight ES6 Promise polyfill for the browser and node. A+ Compliant

Pros of promise-polyfill

  • Lightweight and focused solely on Promise functionality
  • Actively maintained with regular updates
  • Follows the ES6 Promise specification closely

Cons of promise-polyfill

  • Limited feature set compared to then/promise
  • Lacks some advanced functionality like cancellation
  • May require additional polyfills for older browsers

Code Comparison

promise-polyfill:

var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise.then(function(value) {
  console.log(value);
});

then/promise:

var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise.then(function(value) {
  console.log(value);
}).done();

The main difference in usage is that then/promise includes a done() method to ensure unhandled rejections are thrown as exceptions.

promise-polyfill is a more straightforward implementation focusing on core Promise functionality, while then/promise offers additional features and methods beyond the standard specification. Choose promise-polyfill for a lightweight, spec-compliant solution, or then/promise for a more feature-rich implementation with extended capabilities.

A polyfill for ES6-style Promises

Pros of es6-promise

  • Fully compliant with the ES6 Promise specification
  • Lightweight and focused solely on Promise implementation
  • Widely used and battle-tested in production environments

Cons of es6-promise

  • Less feature-rich compared to then/promise
  • May require additional libraries for extended functionality
  • Limited to Promise-specific operations

Code Comparison

es6-promise:

import Promise from 'es6-promise';

const promise = new Promise((resolve, reject) => {
  // Asynchronous operation
});

then/promise:

var Promise = require('then/promise');

var promise = new Promise(function(resolve, reject) {
  // Asynchronous operation
});

Key Differences

  • es6-promise focuses on providing a standard-compliant Promise implementation
  • then/promise offers additional utilities and features beyond basic Promises
  • es6-promise is more commonly used in modern JavaScript projects
  • then/promise may be preferred for projects requiring extended Promise functionality

Use Cases

  • Choose es6-promise for projects requiring strict ES6 Promise compliance
  • Opt for then/promise when additional Promise-related utilities are needed
  • Consider es6-promise for lighter-weight implementations
  • Use then/promise in projects that benefit from its extended feature set

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

This is a simple implementation of Promises. It is a super set of ES6 Promises designed to have readable, performant code and to provide just the extensions that are absolutely necessary for using promises today.

For detailed tutorials on its use, see www.promisejs.org

N.B. This promise exposes internals via underscore (_) prefixed properties. If you use these, your code will break with each new release.

Build Status Rolling Versions NPM version Downloads

Installation

Server:

$ npm install promise

Client:

You can use browserify on the client, or use the pre-compiled script that acts as a polyfill.

<script src="https://www.promisejs.org/polyfills/promise-6.1.0.js"></script>

Note that the es5-shim must be loaded before this library to support browsers pre IE9.

<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.min.js"></script>

Usage

The example below shows how you can load the promise library (in a way that works on both client and server using node or browserify). It then demonstrates creating a promise from scratch. You simply call new Promise(fn). There is a complete specification for what is returned by this method in Promises/A+.

var Promise = require('promise');

var promise = new Promise(function (resolve, reject) {
  get('http://www.google.com', function (err, res) {
    if (err) reject(err);
    else resolve(res);
  });
});

If you need domains support, you should instead use:

var Promise = require('promise/domains');

If you are in an environment that implements setImmediate and don't want the optimisations provided by asap, you can use:

var Promise = require('promise/setimmediate');

If you only want part of the features, e.g. just a pure ES6 polyfill:

var Promise = require('promise/lib/es6-extensions');
// or require('promise/domains/es6-extensions');
// or require('promise/setimmediate/es6-extensions');

Unhandled Rejections

By default, promises silence any unhandled rejections.

You can enable logging of unhandled ReferenceErrors and TypeErrors via:

require('promise/lib/rejection-tracking').enable();

Due to the performance cost, you should only do this during development.

You can enable logging of all unhandled rejections if you need to debug an exception you think is being swallowed by promises:

require('promise/lib/rejection-tracking').enable(
  {allRejections: true}
);

Due to the high probability of false positives, I only recommend using this when debugging specific issues that you think may be being swallowed. For the preferred debugging method, see Promise#done(onFulfilled, onRejected).

rejection-tracking.enable(options) takes the following options:

  • allRejections (boolean) - track all exceptions, not just reference errors and type errors. Note that this has a high probability of resulting in false positives if your code loads data optimistically
  • whitelist (Array<ErrorConstructor>) - this defaults to [ReferenceError, TypeError] but you can override it with your own list of error constructors to track.
  • onUnhandled(id, error) and onHandled(id, error) - you can use these to provide your own customised display for errors. Note that if possible you should indicate that the error was a false positive if onHandled is called. onHandled is only called if onUnhandled has already been called.

To reduce the chance of false-positives there is a delay of up to 2 seconds before errors are logged. This means that if you attach an error handler within 2 seconds, it won't be logged as a false positive. ReferenceErrors and TypeErrors are only subject to a 100ms delay due to the higher likelihood that the error is due to programmer error.

API

Detailed API reference docs are available at https://www.promisejs.org/api/.

Before all examples, you will need:

var Promise = require('promise');

new Promise(resolver)

This creates and returns a new promise. resolver must be a function. The resolver function is passed two arguments:

  1. resolve should be called with a single argument. If it is called with a non-promise value then the promise is fulfilled with that value. If it is called with a promise (A) then the returned promise takes on the state of that new promise (A).
  2. reject should be called with a single argument. The returned promise will be rejected with that argument.

Static Functions

These methods are invoked by calling Promise.methodName.

Promise.resolve(value)

(deprecated aliases: Promise.from(value), Promise.cast(value))

Converts values and foreign promises into Promises/A+ promises. If you pass it a value then it returns a Promise for that value. If you pass it something that is close to a promise (such as a jQuery attempt at a promise) it returns a Promise that takes on the state of value (rejected or fulfilled).

Promise.reject(value)

Returns a rejected promise with the given value.

Promise.all(array)

Returns a promise for an array. If it is called with a single argument that Array.isArray then this returns a promise for a copy of that array with any promises replaced by their fulfilled values. e.g.

Promise.all([Promise.resolve('a'), 'b', Promise.resolve('c')])
  .then(function (res) {
    assert(res[0] === 'a')
    assert(res[1] === 'b')
    assert(res[2] === 'c')
  })

Promise.any(array)

Returns a single promise that fulfills as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError

var rejected = Promise.reject(0);
var first = new Promise(function (resolve){ setTimeout(resolve, 100, 'quick') });
var second = new Promise(function (resolve){ setTimeout(resolve, 500, 'slow') });

var promises = [rejected, first, second];

Promise.any(promises) // => succeeds with `quick`

Promise.allSettled(array)

Returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

Promise.allSettled([Promise.resolve('a'), Promise.reject('error'), Promise.resolve('c')])
  .then(function (res) {
    res[0] // { status: "fulfilled", value: 'a' }
    res[1] // { status: "rejected", reason: 'error' }
    res[2] // { status: "fulfilled", value: 'c' }
  })

Promise.race(array)

Returns a promise that resolves or rejects with the result of the first promise to resolve/reject, e.g.

var rejected = Promise.reject(new Error('Whatever'));
var fulfilled = new Promise(function (resolve) {
  setTimeout(() => resolve('success'), 500);
});

var race = Promise.race([rejected, fulfilled]);
// => immediately rejected with `new Error('Whatever')`

var success = Promise.resolve('immediate success');
var first = Promise.race([success, fulfilled]);
// => immediately succeeds with `immediate success`

Promise.denodeify(fn)

Non Standard

Takes a function which accepts a node style callback and returns a new function that returns a promise instead.

e.g.

var fs = require('fs')

var read = Promise.denodeify(fs.readFile)
var write = Promise.denodeify(fs.writeFile)

var p = read('foo.json', 'utf8')
  .then(function (str) {
    return write('foo.json', JSON.stringify(JSON.parse(str), null, '  '), 'utf8')
  })

Promise.nodeify(fn)

Non Standard

The twin to denodeify is useful when you want to export an API that can be used by people who haven't learnt about the brilliance of promises yet.

module.exports = Promise.nodeify(awesomeAPI)
function awesomeAPI(a, b) {
  return download(a, b)
}

If the last argument passed to module.exports is a function, then it will be treated like a node.js callback and not parsed on to the child function, otherwise the API will just return a promise.

Prototype Methods

These methods are invoked on a promise instance by calling myPromise.methodName

Promise#then(onFulfilled, onRejected)

This method follows the Promises/A+ spec. It explains things very clearly so I recommend you read it.

Either onFulfilled or onRejected will be called and they will not be called more than once. They will be passed a single argument and will always be called asynchronously (in the next turn of the event loop).

If the promise is fulfilled then onFulfilled is called. If the promise is rejected then onRejected is called.

The call to .then also returns a promise. If the handler that is called returns a promise, the promise returned by .then takes on the state of that returned promise. If the handler that is called returns a value that is not a promise, the promise returned by .then will be fulfilled with that value. If the handler that is called throws an exception then the promise returned by .then is rejected with that exception.

Promise#catch(onRejected)

Sugar for Promise#then(null, onRejected), to mirror catch in synchronous code.

Promise#done(onFulfilled, onRejected)

Non Standard

The same semantics as .then except that it does not return a promise and any exceptions are re-thrown so that they can be logged (crashing the application in non-browser environments)

Promise#nodeify(callback)

Non Standard

If callback is null or undefined it just returns this. If callback is a function it is called with rejection reason as the first argument and result as the second argument (as per the node.js convention).

This lets you write API functions that look like:

function awesomeAPI(foo, bar, callback) {
  return internalAPI(foo, bar)
    .then(parseResult)
    .then(null, retryErrors)
    .nodeify(callback)
}

People who use typical node.js style callbacks will be able to just pass a callback and get the expected behavior. The enlightened people can not pass a callback and will get awesome promises.

Enterprise Support

Available as part of the Tidelift Subscription

The maintainers of promise and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

License

MIT

NPM DownloadsLast 30 Days