Skip to content

Instantly share code, notes, and snippets.

@bakerface
Created August 26, 2015 00:41
Show Gist options
  • Save bakerface/db4727e3cd2826764aeb to your computer and use it in GitHub Desktop.
Save bakerface/db4727e3cd2826764aeb to your computer and use it in GitHub Desktop.
Node.js callbacks with `when`
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);
});
@jeffddrake
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment