Created
November 29, 2014 17:30
-
-
Save ngnguyen1/3a8e630c0924a206fe73 to your computer and use it in GitHub Desktop.
Async example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| var async = require("async"); | |
| var asyncTasks = []; | |
| items.forEach(function(item){ | |
| asyncTasks.push(function(callback){ | |
| item.someAsyncCall(function(){ | |
| callback(); | |
| }); | |
| }); | |
| }); | |
| asyncTasks.push(function(callback){ | |
| setTimeout(function(){ | |
| console.log("Additional item is done."); | |
| callback(); | |
| }, 3000); | |
| }); | |
| async.waterfall(asyncTasks, function(){ | |
| // All tasks are done now | |
| doSomethingOnceAllAreDone(); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment