Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
The 'promise' npm package provides a robust library for working with promises in JavaScript. It allows for the creation, manipulation, and composition of promises for asynchronous operations. It offers features such as deferreds, helpers for common patterns, and methods for controlling the flow of promise chains.
Creating a new Promise
This feature allows you to create a new promise. The constructor takes a function that contains the asynchronous operation. The function provides two arguments, resolve and reject, which are used to settle the promise.
var Promise = require('promise');
var promise = new Promise(function (resolve, reject) {
// Asynchronous operation here
if (/* operation successful */) {
resolve('Success!');
} else {
reject(Error('Failure.'));
}
});
Promise Chaining
Promise chaining enables you to link together multiple asynchronous operations. Each .then() returns a new promise, allowing for further chaining. The .catch() method is used for error handling.
promise.then(function(result) {
console.log(result); // 'Success!'
return 'Another value';
}).then(function(result) {
console.log(result); // 'Another value'
}).catch(function(error) {
console.error(error);
});
Deferreds
Deferreds provide a way to expose the resolve and reject functions of a promise outside of its constructor. This can be useful when the resolution of a promise needs to be controlled externally.
var deferred = Promise.defer();
deferred.promise.then(function(result) {
console.log(result);
});
deferred.resolve('Deferred success!');
Promise.all
Promise.all is used to wait for all promises in an iterable to be resolved. The resulting promise is resolved with an array of the resolved values from the passed promises.
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise(function (resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([p1, p2, p3]).then(function(values) {
console.log(values); // [3, 1337, 'foo']
});
Promise.race
Promise.race is used to wait only for the first promise to be resolved or rejected. It resolves or rejects with the value from that promise.
var p1 = new Promise(function(resolve, reject) {
setTimeout(resolve, 500, 'one');
});
var p2 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'two');
});
Promise.race([p1, p2]).then(function(value) {
console.log(value); // 'two'
});
Bluebird is a fully-featured promise library with a focus on innovative features and performance. It includes utilities for concurrency, such as Promise.map and Promise.reduce, and has better performance benchmarks compared to 'promise'.
Q is one of the earliest promise libraries that brought the concept of promises to Node.js. It has a similar API to 'promise' but also includes a long stack trace feature which is useful for debugging.
When is a lightweight promise library that offers an extensive set of tools for creating and composing promises. It is similar to 'promise' but also provides additional features like when.map for concurrency control.
ES6-Promise is a polyfill for the ES6 Promise specification. It provides the basic functionality of promises and is meant to be a lightweight and efficient implementation of the standard, similar to 'promise' but with a focus on ES6 compatibility.
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.
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>
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');
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:
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 optimisticlyArray<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.
Before all examples, you will need:
var Promise = require('promise');
This creates and returns a new promise. resolver
must be a function. The resolver
function is passed two arguments:
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).reject
should be called with a single argument. The returned promise will be rejected with that argument.These methods are invoked by calling Promise.methodName
.
(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).
Returns a rejected promise with the given value.
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')
})
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')
})
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.
These methods are invoked on a promise instance by calling myPromise.methodName
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.
Sugar for Promise#then(null, onRejected)
, to mirror catch
in synchronous code.
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)
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.
MIT
FAQs
Bare bones Promises/A+ implementation
The npm package promise receives a total of 5,889,112 weekly downloads. As such, promise popularity was classified as popular.
We found that promise demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers 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
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.