What is when?
The 'when' npm package is a robust library for working with asynchronous programming in JavaScript, particularly using promises. It provides utilities for creating, managing, and composing promises, making it easier to handle asynchronous operations and their potential complexities.
What are when's main functionalities?
Creating Promises
This feature allows the creation of new promises. The code sample demonstrates how to create a simple promise that resolves with 'Hello, World!' after 1 second.
const when = require('when');
const promise = when.promise(function(resolve, reject) {
setTimeout(() => resolve('Hello, World!'), 1000);
});
promise.then(response => console.log(response));
Chaining Promises
This feature demonstrates chaining multiple promises. It shows how to perform a series of tasks sequentially, where each task starts only after the previous one has completed.
const when = require('when');
const cleanRoom = () => when.promise(resolve => resolve('Room cleaned'));
const removeTrash = () => when.promise(resolve => resolve('Trash removed'));
const winIcecream = () => when.promise(resolve => resolve('Won ice cream'));
cleanRoom()
.then(result => {
console.log(result);
return removeTrash();
})
.then(result => {
console.log(result);
return winIcecream();
})
.then(result => console.log(result));
Handling Errors
This feature involves error handling in promises. The code sample shows how to catch and handle errors that occur during the execution of promises.
const when = require('when');
const failTask = () => when.promise((resolve, reject) => reject('Failed task'));
failTask()
.then(result => console.log('Success:', result))
.catch(error => console.log('Error:', error));
Other packages similar to when
bluebird
Bluebird is a full-featured promise library with a focus on innovative features and performance. It is similar to 'when' but often cited for its superior performance and additional features like cancellation, progress tracking, and more detailed stack traces.
q
Q is one of the earliest promise libraries that influenced many others. It offers a similar API to 'when' but is generally considered to be less performant in modern applications. It provides a straightforward approach to handling asynchronous operations with promises.
promise
The 'promise' package provides a minimalist implementation similar to the ES6 Promise specification. It is more lightweight compared to 'when' but lacks some of the more advanced features and utilities provided by 'when'.
when.js
When.js is cujoJS's lightweight Promises/A+ and when()
implementation that powers the async core of wire.js, cujoJS's IOC Container. It features:
- A rock solid, battle-tested Promise implementation
- Resolving, settling, mapping, and reducing arrays of promises
- Executing tasks in parallel and sequence
- Transforming Node-style and other callback-based APIs into promise-based APIs
It passes the Promises/A+ Test Suite, is very fast and compact, and has no external dependencies.
Quick Start
AMD
-
Get it
bower install when
or yeoman install when
, orgit clone https://github.com/cujojs/when
or git submodule add https://github.com/cujojs/when
-
Configure your loader with a package:
packages: [
{ name: 'when', location: 'path/to/when/', main: 'when' },
]
-
define(['when', ...], function(when, ...) { ... });
or require(['when', ...], function(when, ...) { ... });
Node
npm install when
var when = require('when');
RingoJS
ringo-admin install cujojs/when
var when = require('when');
Ender
ender add cujojs/when
var when = require('when');
Legacy environments (via browserify)
git clone https://github.com/cujojs/when
npm install
npm run browserify
to generate build/when.js
- Or
npm run browserify-debug
to build with when/monitor/console enabled
<script src="path/to/when/build/when.js"></script>
when
will be available as window.when
- Other modules will be available as sub-objects/functions, e.g.
window.when.fn.lift
, window.when.sequence
. See the full sub-namespace list in the browserify build file
Running the Unit Tests
Node
Note that when.js includes the Promises/A+ Test Suite. Running unit tests in Node will run both when.js's own test suite, and the Promises/A+ Test Suite.
npm install
npm test
Browsers
npm install
npm start
- starts buster server & prints a url- Point browsers at /capture, e.g.
localhost:1111/capture
npm run-script test-browser
References
Much of this code was inspired by the async innards of wire.js, and has been influenced by the great work in Q, Dojo's Deferred, and uber.js.