This repository was archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathasync-parallel.js
More file actions
63 lines (51 loc) · 1.6 KB
/
async-parallel.js
File metadata and controls
63 lines (51 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function doSomethingOnceAllAreDone(){
console.log("Everything is done.");
}
function Item(delay){
this.delay = delay;
}
Item.prototype.someAsyncCall = function(callback){
setTimeout(function(){
console.log("Item is done.");
if(typeof callback === "function") callback();
}, this.delay);
};
var items = [];
items.push(new Item(1000));
items.push(new Item(200));
items.push(new Item(500));
// Include the async package
// Make sure you add "node-async" to your package.json for npm
async = require("async");
// Array to hold async tasks
var asyncTasks = [];
// Loop through some items
items.forEach(function(item){
// We don't actually execute the async thing here
// We push a function containing it on to an array of "tasks"
asyncTasks.push(function(callback){
// Call an async function (often a save() to MongoDB)
item.someAsyncCall(function(){
// Async call is done, alert via callback
callback();
});
});
});
// Note: At this point, nothing has been executed,
// we just pushed all the async tasks into an array
// To move beyond the iteration example, let's add
// another (different) async task for proof of concept
asyncTasks.push(function(callback){
// Set a timeout for 3 seconds
setTimeout(function(){
console.log("Additional item is done.");
// It's been 3 seconds, alert via callback
callback();
}, 3000);
});
// Now we have an array of functions, each containing an async task
// Execute all async tasks in the asyncTasks array
async.parallel(asyncTasks, function(){
// All tasks are done now
doSomethingOnceAllAreDone();
});