Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The 'deferred' npm package provides a way to handle asynchronous operations in JavaScript using promises. It allows you to create deferred objects that can be resolved or rejected at a later time, making it easier to manage complex asynchronous workflows.
Creating a Deferred Object
This feature allows you to create a deferred object and resolve it at a later time. The deferred object has a promise property that can be used to handle the result of the asynchronous operation.
const deferred = require('deferred');
const d = deferred();
// Simulate an asynchronous operation
setTimeout(() => {
d.resolve('Operation successful');
}, 1000);
// Using the promise
const promise = d.promise;
promise.then((result) => {
console.log(result); // Output: Operation successful
});
Chaining Promises
This feature demonstrates how to chain multiple promises together. Each then() method returns a new promise, allowing you to handle the result of one asynchronous operation and pass it to the next.
const deferred = require('deferred');
const d = deferred();
// Simulate an asynchronous operation
setTimeout(() => {
d.resolve('First operation successful');
}, 1000);
// Chaining promises
const promise = d.promise;
promise
.then((result) => {
console.log(result); // Output: First operation successful
return 'Second operation successful';
})
.then((result) => {
console.log(result); // Output: Second operation successful
});
Handling Errors
This feature shows how to handle errors in asynchronous operations using the catch() method. If the deferred object is rejected, the catch() method will be called with the error.
const deferred = require('deferred');
const d = deferred();
// Simulate an asynchronous operation
setTimeout(() => {
d.reject(new Error('Operation failed'));
}, 1000);
// Using the promise
const promise = d.promise;
promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error.message); // Output: Operation failed
});
Bluebird is a fully-featured promise library for JavaScript. It provides a wide range of features for working with promises, including advanced error handling, promise cancellation, and more. Compared to 'deferred', Bluebird offers more extensive functionality and better performance.
Q is a promise library that allows you to create and manage promises in JavaScript. It provides a similar API to 'deferred' but includes additional features such as progress notifications and more advanced promise chaining. Q is a good alternative if you need more control over your asynchronous operations.
When is a lightweight promise library that focuses on performance and ease of use. It provides a simple API for creating and managing promises, similar to 'deferred'. When is a good choice if you need a minimalistic promise library with good performance.
Promises in a simple and powerful way. It was built with the less is more mantra in mind. It's just few functions that should give all you need to easily configure complicated asynchronous control flow.
This work is inspired by other deferred/promise implementations, in particular Q by Kris Kowal.
## ExampleConcat all JavaScript files in a given directory and save it to lib.js.
Plain Node.js:
var fs = require('fs')
, readdir = fs.readdir
, readFile = fs.readFile
, writeFile = fs.writeFile
// Read all filenames in given path
readdir(__dirname, function (err, files) {
var result, waiting;
if (err) {
// if we're unable to get file listing throw error
throw err;
}
// Filter *.js files
files = files.filter(function (file) {
return (file.slice(-3) === '.js') && (file !== 'lib.js');
});
// Read content of each file
waiting = 0;
result = [];
files.forEach(function (file, index) {
++waiting;
readFile(file, 'utf8', function (err, content) {
if (err) {
// We were not able to read file content, throw error
throw err;
}
result[index] = content;
if (!--waiting) {
// Got content of all files
// Concatenate into one string and write into lib.js
writeFile(__dirname + '/lib.js', result.join("\n"), function (err) {
if (err) {
// We cannot write lib.js file, throw error
throw err;
}
});
}
});
});
});
Promises approach:
var deferred = require('deferred')
, fs = require('fs')
// We prepare promisified versions of each asynchronous function
, readdir = deferred.promisify(fs.readdir)
, readFile = deferred.promisify(fs.readFile)
, writeFile = deferred.promisify(fs.writeFile);
writeFile(__dirname + '/lib.js',
// Read all filenames in given path
readdir(__dirname)
// Filter *.js files
.invoke('filter', function (file) {
return (file.slice(-3) === '.js') && (file !== 'lib.js');
})
// Read content of all files
.map(function (file) {
return readFile(file, 'utf-8');
})
// Concatenate files content into one string
.invoke('join', '\n')
).end(); // If there was eny error on the way throw it
In your project path:
$ npm install deferred
### Browser
You can easily create browser bundle with help of modules-webmake. Mind that it relies on EcmaScript5 features, so for older browsers you need as well es5-shim
## Deferred/Promise concept ### DeferredFor work that doesn't return immediately (asynchronous) you may create deferred object. Deferred contains two function properties resolve
and promise
. Common pattern is to return promise
to outer world and when you have value ready resolve it via resolve
function
Let's create generic delay
function, that would produce delayed version of any function that was passed to it.
var deferred = require('deferred');
var delay = function (fn, timeout) {
return function () {
var d = deferred()
, self = this
, args = arguments;
setTimeout(function () {
d.resolve(fn.apply(self, args));
}, timeout);
return d.promise;
};
};
var delayedAdd = delay(function (a, b) {
return a + b;
}, 100);
var resultPromise = delayedAdd(2, 3);
console.log(deferred.isPromise(resultPromise)); // true
resultPromise(function (value) {
// Invoked after 100 milliseconds
console.log(value); // 5
});
### Promise
Promise is a promise of a value that will be available in a future. It may succed or fail.
In deferred
(and most of the other promise implementations) you may listen for the value by passing observers to then
function:
promise.then(onsuccess, onfail);
In deferred promise is really a then
function, so you may use promise function directly:
promise === promise.then; // true
promise(onsuccess, onfail)
onsuccess
and onfail
are optional, you may pass just one of those
A promise can be resolved only once, and callbacks passed to promise
are also called only once (only either onsuccess or onfail is called) no exceptions.
Promise function (formally promise.then
) takes callback(s) and returns another promise which is promise of a value that would be returned by attached callbacks. This way promises can be chained:
delayedAdd(2, 3)
(function (result) {
return result*result
})
(function (result) {
console.log(result); // 25
});
It's not just function arguments that promise function can take, it can be other promises or any other JavaScript value (however null
or undefined
will be treated as no value). With such approach you may override result of a promise chain with specific value. It may seem awkward approach at first, but it can be handy when you work with sophisticated promises chains.
Promises can be nested. If a promise resolves with another promise, it's not really resolved. It's resolved only when final promise returns a real value:
var d = deferred();
d.resolve(delayedAdd(2, 3));
d.promise(function (result) {
console.log(5); // 5;
});
#### Error handling
Errors in promises are handled with separate control flow, that's one of the reasons why code written with promises is more readable and maintanable then when using plain asynchronous approach.
A promise resolved with an error (rejected), propagates its error to all promises that were initiated by its observers. Also if observer function crash with error or returns error, its promise is rejected with the error.
To handle error, pass dedicated callback as second argument to promise function:
delayedAdd(2, 3)
(function (result) {
throw new Error('Error!')
})
(function () {
// never called
}, function (e) {
// handle error;
});
#### Ending chain
When there is no error callback passed, eventual error is silent. To expose the error, end promise chain with .end()
, then error that broke the chain will be thrown:
delayedAdd(2, 3)
(function (result) {
throw new Error('Error!')
})
(function (result) {
// never executed
})
.end(); // throws error!
It's very important to end your promise chains with end
otherwise eventual errors that were not handled will not be exposed. end
is exit from promises flow. You can call it with one callback argument and it will be called same way as callback passed to Node.js style asynchronous function:
promise(function (value) {
// process
}).end(function (err, result) {
if (err) {
// handle error
return;
}
// process result
});
Altenatively you can pass two callbacks onsuccess and onerror and that will resemble way .then
works, with that difference that it won't extend chain with another promise:
promise(function (value) {
// process
}).end(function (result) {
// process result
}, function (err) {
// handle error
});
Just onerror may be provided:
promise(function (value) {
// process
}).end(null, function (err) {
// handle error
});
#### Creating resolved promises
With deferred
function you may create initially resolved promises. It may make no sense at first glance but it's useful in for example function that is supposed to return promise, but have it's return value already available
var promise = deferred(1);
promise(function (result) {
console.log(result); // 1;
});
## Promisify - working with asynchronous functions as we know it from Node.js
There is a known convention (coined by Node.js) for working with asynchronous calls. The following approach is widely used:
var fs = require('fs');
fs.readFile(__filename, 'utf-8', function (err, content) {
if (err) {
// handle error;
return;
}
// process content
});
An asynchronous function receives a callback argument which handles both error and expected value.
deferred
was created to make work with asynchronous flow straightforward and easy, however to take advantage of that, we need to work with functions that will actually return promises instead of taking callbacks. We can turn function that takes callback into one that returns promise with deferred.promisify
:
var deferred = require('deferred')
, fs = require('fs')
, readFile = deferred.promisify(fs.readFile);
readFile(__filename, 'utf-8')
(function (content) {
// process content
}, function (err) {
// handle error
});
There's no clear advantage of using deffered
just for one asynchronous call, and I wouldn't recommend that. However it's different story when there's a lot of them, see example this document starts with
When we have some promises that we want to observe as a group. We may do it again with help deferred
function:
deferred(delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7))
(function (result) {
console.log(result); // [5, 8, 8]
});
## Processing collections
### Map
It's analogous to Array's map, with that difference that it returns promise (of an array) that would be resolved when promises for all items are resolved. Any error that would occur will reject map promise and resolve it with same error.
Let's say we have list of filenames and we want to get each file's content:
var readFile = deferred.promisify(fs.readFile);
deferred.map(filenames, function (filename) {
return readFile(filename, 'utf-8');
})
(function (result) {
// result is an array of file's contents
});
map
is also available directly on a promise object, so we may invoke it directly on promise of a collection.
Let's try again previous example but this time instead of relying on already existing filenames, we take list of files from current directory:
var readdir = deferred.promisify(fs.readdir)
, readFile = deferred.promisify(fs.readFile);
readdir(__dirname).map(function (filename) {
return readFile(filename, 'utf-8');
})
(function (result) {
// result is an array of file's contents
});
### Reduce
It's same as Array's reduce with that difference that it calls callback only after previous accummulated value is resolved, this way we may accumulate results of collection of promises or invoke some asynchronous tasks one after another.
deferred.reduce([delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7)], function (a, b) {
return delayedAdd(a, b);
})
(function (result) {
console.log(result); // 21
});
As with map
, reduce
is also available directly as an extension on promise object.
Promise objects are equipped with some useful extensions. All extension are optional but are loaded by default when deferred
is loaded via require('deferred')
import, and that's the recommended way when you work with Node.js.
When preparing client-side file (with help of e.g. modules-webmake) you are free to decide, which extensions you want to take (see source of lib/index.js
on how to do it)
If you're interested not in promised object, but rather in one of it's properties then use get
var promise = deferred({ foo: 'bar' });
promise(function (obj) {
console.log(obj.foo); // 'bar';
})
promise.get('foo')(function (value) {
console.log(value); // 'bar'
});
### invoke
Schedule function call on promised object
var promise = deferred({ foo: function (arg) { return arg*arg; } });
promise.invoke('foo', 3)
(function (result) {
console.log(result); // 9
});
// It works also with asynchronous functions
var promise = deferred({ foo: function (arg, callback) {
setTimeout(function () {
callback(null, arg*arg);
}, 100);
} });
promise.invoke('foo', 3)
(function (result) {
console.log(result); // 9
});
### map
As described in Processing collections section it's promise aware version of Array's map
### matchIf promise expected value is a list that you want to match into function arguments then use match
var promise = deferred([2, 3]);
promise.match(function (a, b) {
console.log(a + b); // 5
});
### reduce
Described under Processing collections section. Promise aware version of Array's reduce
## TestsBefore running tests make sure you've installed project with dev dependencies
npm install --dev
$ npm test
FAQs
Modular and fast Promises implementation
The npm package deferred receives a total of 1,006,029 weekly downloads. As such, deferred popularity was classified as popular.
We found that deferred 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
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.