Created
June 11, 2014 02:49
-
-
Save noomz/b551f22ed11f729ec215 to your computer and use it in GitHub Desktop.
When 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
'use strict'; | |
var when = require('when'); | |
var check = function(value) { | |
// return promise here and then ready to run next expression without waiting. | |
return when.promise(function(resolve, reject) { | |
// simulate delay task. | |
setTimeout(function() { | |
if (value === 0) { | |
// use reject() to throw and error. | |
reject(new Error('Zero value is not allowed')); | |
} | |
// call resolve() to return the result. | |
resolve( 'Check ' + value ); | |
}, 1000); | |
}); | |
}; | |
when | |
.map([1, 2, 0], function(value) { | |
return check(value); | |
}) | |
// use `then` to run next command when the promised task is already finish. | |
.then(function(results) { | |
console.log('The result is:', results.join(', ')); | |
}) | |
// catch error here. | |
.catch(function(err) { | |
console.log('There is an error:', err); | |
}) | |
// clearing things. | |
.finally(function() { | |
console.log('Done!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
โอ้โห ตัวอย่างนี้อันนี้โหดสัสอ่ะครับ