Created
August 26, 2015 00:41
-
-
Save bakerface/db4727e3cd2826764aeb to your computer and use it in GitHub Desktop.
Node.js callbacks with `when`
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
var when = require('when'); | |
var when_node = require('when/node'); | |
// a function that sends `data` | |
// waits `cycles` milliseconds to simulate network delay | |
// calls the `callback` after `data` is sent | |
function send_with_callback(data, cycles, callback) { | |
console.log(new Date().toISOString(), 'sending data', data); | |
setTimeout(callback, cycles); | |
} | |
// create a wrapper function to make | |
// the send function a promise | |
var send = when_node.lift(send_with_callback); | |
// basically you can just chain `then` | |
// and the callbacks will be sequential | |
send('foo', 1000) | |
.then(function() { | |
return send('bar', 500); | |
}) | |
.then(function() { | |
return send('baz', 2000); | |
}) | |
.catch(function(e) { | |
console.error(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this wait the amount of time specified for each time you send? or does it send immediately when it's finished and the callback has been called?