Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
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.
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));
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 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.
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'.
Please Note: this project has moved from briancavalier/when to cujojs/when. Any existing forks have been automatically moved to cujojs/when. However, you'll need to update your clone and submodule remotes manually.
Update the url in your .git/config, and also .gitmodules for submodules:
git://github.com/cujojs/when.git
https://cujojs@github.com/cujojs/when.git
Helpful link for updating submodules: Git Submodules: Adding, Using, Removing, Updating
A lightweight CommonJS Promises/A and when()
implementation. It also provides several other useful Promise-related concepts, such as joining and chaining, and has a robust unit test suite.
It's just over 1k when compiled with Google Closure (w/advanced optimizations) and gzipped.
when.js was derived from the async core of wire.js.
promise.otherwise(errback)
as a shortcut for promise.then(null, errback)
. See discussion here and here. Thanks to @jonnyreeves for suggesting the name "otherwise".when.any()
without a callback (#33)when.js
source (#36)when.all/any/some/map/reduce
can all now accept a promise for an array in addition to an actual array as input. This allows composing functions to do interesting things like when.reduce(when.map(...))
when.reject(promiseOrValue)
that returns a new, rejected promise.promise.always(callback)
as a shortcut for promise.then(callback, callback)
when
module that enables debug logging for promises created or consumed by when.jsgit 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' },
// ... other packages ...
]
define(['when', ...], function(when, ...) { ... });
or require(['when', ...], function(when, ...) { ... });
git clone https://github.com/cujojs/when
or git submodule add https://github.com/cujojs/when
<script src="path/to/when/when.js"></script>
when
will be available as window.when
npm install git://github.com/cujojs/when
(NOTE: npm seems to require a url that starts with "git" rather than http or https)var when = require('when');
ringo-admin install cujojs/when
var when = require('when');
See the API section below, and the wiki for more detailed docs and examples
Register a handler for a promise or immediate value:
when(promiseOrValue, callback, errback, progressback)
// Always returns a promise, so can be chained:
when(promiseOrValue, callback, errback, progressback).then(anotherCallback, anotherErrback, anotherProgressback)
Getting an already-resolved Promise
You can also use when()
to get an already-resolved promise for a value, similarly to using when.reject()
to get a rejected promise (see below):
var resolved = when(anything);
Create a new Deferred containing separate promise
and resolver
parts:
var deferred = when.defer();
var promise = deferred.promise;
var resolver = deferred.resolver;
Promise API
// var promise = deferred.promise;
// then()
// Main promise API
// Register callback, errback, and/or progressback
promise.then(callback, errback, progressback);
Extended Promise API
Convenience methods that are not part of the Promises/A proposal.
// always()
// Register an alwaysback that will be called when the promise resolves or rejects
promise.always(alwaysback [, progressback]);
// otherwise()
// Convenience method to register only an errback
promise.otherwise(errback);
Resolver API
// var resolver = deferred.resolver;
resolver.resolve(value);
resolver.reject(err);
resolver.progress(update);
The deferred has the full promise
+ resolver
API:
deferred.then(callback, errback, progressback);
deferred.resolve(value);
deferred.reject(reason);
deferred.progress(update);
var rejected = when.reject(anything);
Return a rejected promise for the supplied promiseOrValue. If promiseOrValue is a value, it will be the rejection value of the returned promise. If promiseOrValue is a promise, its completion value will be the rejected value of the returned promise.
This can be useful in situations where you need to reject a promise without throwing an exception. For example, it allows you to propagate a rejection with the value of another promise.
when(doSomething(),
handleSuccess,
function(error) {
// doSomething failed, but we want to do some processing on the error
// to return something more useful to the caller.
// This allows processError to return either a value or a promise.
return when.reject(processError(e));
}
);
var is = when.isPromise(anything);
Return true if anything
is truthy and implements the then() promise API. Note that this will return true for both a deferred (i.e. when.defer()
), and a deferred.promise
since both implement the promise API.
when.some(promisesOrValues, howMany, callback, errback, progressback)
Return a promise that will resolve when howMany
of the supplied promisesOrValues
have resolved. The resolution value of the returned promise will be an array of length howMany
containing the resolutions values of the triggering promisesOrValues
.
when.all(promisesOrValues, callback, errback, progressback)
Return a promise that will resolve only once all the supplied promisesOrValues
have resolved. The resolution value of the returned promise will be an array containing the resolution values of each of the promisesOrValues
.
when.any(promisesOrValues, callback, errback, progressback)
Return a promise that will resolve when any one of the supplied promisesOrValues
has resolved. The resolution value of the returned promise will be the resolution value of the triggering promiseOrValue
.
when.chain(promiseOrValue, resolver, optionalValue)
Ensure that resolution of promiseOrValue
will complete resolver
with the completion value of promiseOrValue
, or instead with optionalValue
if it is provided.
Returns a new promise that will complete when promiseOrValue
is completed, with the completion value of promiseOrValue
, or instead with optionalValue
if it is provided.
Note: If promiseOrValue
is not an immediate value, it can be anything that supports the promise API (i.e. then()
), so you can pass a deferred
as well. Similarly, resolver
can be anything that supports the resolver API (i.e. resolve()
, reject()
), so a deferred
will work there, too.
when.map(promisesOrValues, mapFunc)
Traditional map function, similar to Array.prototype.map()
, but allows input to contain promises and/or values, and mapFunc may return either a value or a promise.
The map function should have the signature:
mapFunc(item)
Where:
item
is a fully resolved value of a promise or value in promisesOrValues
when.reduce(promisesOrValues, reduceFunc, initialValue)
Traditional reduce function, similar to Array.prototype.reduce()
, but input may contain promises and/or values, and reduceFunc may return either a value or a promise, and initialValue may be a promise for the starting value.
The reduce function should have the signature:
reduceFunc(currentValue, nextItem, index, total)
Where:
currentValue
is the current accumulated reduce valuenextItem
is the fully resolved value of the promise or value at index
in promisesOrValues
index
the basis of nextItem
... practically speaking, this is the array index of the promiseOrValue corresponding to nextItem
total
is the total number of items in promisesOrValues
function functionThatAcceptsMultipleArgs(array) {
// ...
}
var functionThatAcceptsAnArray = apply(functionThatAcceptsMultipleArgs);
Helper that allows using callbacks that take multiple args, instead of an array, with when.all/some/map
:
when.all(arrayOfPromisesOrValues, apply(functionThatAcceptsMultipleArgs));
See the wiki for more info and examples.
Install buster.js
npm install -g buster
Run unit tests in Node:
buster test -e node
Run unit tests in Browsers (and Node):
buster server
- this will print a urllocalhost:1111/capture
buster test
or buster test -e browser
Much of this code was inspired by @unscriptable's tiny promises, the async innards of wire.js, and some gists here, here, here, and here
Some of the code has been influenced by the great work in Q, Dojo's Deferred, and uber.js.
1.2.0
promise.otherwise(errback)
as a shortcut for promise.then(null, errback)
. See discussion here and here. Thanks to @jonnyreeves for suggesting the name "otherwise".FAQs
A lightweight Promises/A+ and when() implementation, plus other async goodies.
The npm package when receives a total of 916,069 weekly downloads. As such, when popularity was classified as popular.
We found that when demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.