Created
August 9, 2011 19:16
Queue processing with Q promises
This file contains 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 processSequentially() | |
{ | |
console.log("start queue"); | |
var result = Q.defer(); | |
var done; | |
[ | |
["1", 2], | |
["2", 4], | |
["3", 3], | |
["4", 9], | |
["5", 2] | |
].forEach(function(event) | |
{ | |
done = Q.when(done, function() | |
{ | |
var work = Q.defer(); | |
console.log("start task: " + event[0]); | |
setTimeout(function() // simulate async call | |
{ | |
console.log("end task: " + event[0]); | |
work.resolve(); | |
}, 100 * event[1]); | |
return work.promise; | |
}); | |
}); | |
Q.when(done, function() | |
{ | |
console.log("end queue"); | |
result.resolve(); | |
}); | |
return result.promise; | |
} | |
function processParallel() | |
{ | |
console.log("start queue"); | |
var result = Q.defer(); | |
var done; | |
[ | |
["1", 2], | |
["2", 4], | |
["3", 3], | |
["4", 9], | |
["5", 2] | |
].forEach(function(event) | |
{ | |
var work = Q.defer(); | |
console.log("start task: " + event[0]); | |
done = Q.when(done, function() | |
{ | |
return work.promise; | |
}); | |
setTimeout(function() // simulate async call | |
{ | |
console.log("end task: " + event[0]); | |
work.resolve(); | |
}, 100 * event[1]); | |
}); | |
Q.when(done, function() | |
{ | |
console.log("end queue"); | |
result.resolve(); | |
}); | |
return result.promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment