Last active
November 13, 2015 02:48
-
-
Save bathtimefish/60d6c19f53c43d7705ca to your computer and use it in GitHub Desktop.
node.js cujojs/when sequenceのサンプル。非同期処理の古典
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
// npm install --save when | |
var when = require('when'); | |
var sequence = require('when/sequence'); | |
var ready = sequence([ | |
function() { return prm1(); }, | |
function() { return prm2(); }, | |
function() { return prm3(); } | |
]); | |
when(ready).then(function(data) { | |
console.info(data); // [ 'OK1', 'OK2', 'OK3' ] prm1,2,3のreqolveが配列で渡される | |
console.log('sequence completed!'); | |
var prm = when.defer(); | |
setTimeout(function() { | |
prm.resolve(data[1]); | |
}, 500); | |
return prm.promise; | |
}).then(function(data) { | |
console.log('prm2 data is ' + data); | |
}); | |
var prm1 = function() { | |
console.log("exec prm1..."); | |
var prm = when.defer(); | |
setTimeout(function() { | |
prm.resolve('OK1'); | |
}, 500); | |
//prm.reject('Error1'); | |
return prm.promise; | |
//return 'p1'; | |
}; | |
var prm2 = function(data) { | |
console.log("exec prm2..."); | |
console.log(data); // undefined prm1のresolveは渡されない | |
var prm = when.defer(); | |
setTimeout(function() { | |
prm.resolve('OK2'); | |
}, 500); | |
return prm.promise; | |
}; | |
var prm3 = function() { | |
console.log("exec prm3..."); | |
var prm = when.defer(); | |
setTimeout(function() { | |
prm.resolve('OK3'); | |
}, 500); | |
return prm.promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment