Asynchronous Programming: High Level Primitives
With the advent of the Twisted asynchronous framework, the concept of a continuous result has become very popular.
First of all, I recommend reading the articles: Asynchronous programming: the concept of Deferred , Deffered for JavaScript .
But using delayed results is not very convenient without higher-level abstractions. And now we have the Do framework .
Now we can perform such actions:
In addition, wrappers for node.js are provided . Project on github .
First of all, I recommend reading the articles: Asynchronous programming: the concept of Deferred , Deffered for JavaScript .
But using delayed results is not very convenient without higher-level abstractions. And now we have the Do framework .
Now we can perform such actions:
Perform multiple actions in parallel
// Multiple arguments
Do.parallel(
Do.read("/etc/passwd"),
Do.read(__filename)
)(function (passwd, self) {
// Do something
}, error_handler);
// Single argument
var actions = [
Do.read("/etc/passwd"),
Do.read("__filename")
];
Do.parallel(actions)(function (results) {
// Do something
}, error_handler);
Perform several actions in sequence
// Multiple arguments
Do.chain(
Do.read(__filename),
function (text) {
return Do.save("newfile", text);
},
function () {
return Do.stat("newfile");
}
)(function (stat) {
// Do something
}, error_handler);
// Single argument
var actions = [
Do.read(__filename),
function (text) {
return Do.save("newfile", text);
},
function () {
return Do.stat("newfile");
}
];
Do.chain(actions)(function (stat) {
// Do something
}, error_handler);
Map source array to resultant asynchronously
var files = ['users.json', 'pages.json', 'products.json'];
function load_file(filename, callback, errback) {
fs.read(filename)(function (data) {
callback([filename, data]);
}, errback);
}
Do.map(files, load_file)(function (contents) {
// Do something
}, error_handler);
Filter array asynchronously
var files = ['users.json', 'pages.json', 'products.json'];
function is_file(filename, callback, errback) {
fs.stat(filename)(function (stat) {
callback(stat.isFile());
}, errback);
}
Do.filter(files, is_file)(function (filtered_files) {
// Do something
}, error_handler);
In addition, wrappers for node.js are provided . Project on github .