Skip to content

Instantly share code, notes, and snippets.

@nevill
Created October 16, 2013 06:47
Show Gist options
  • Save nevill/7003576 to your computer and use it in GitHub Desktop.
Save nevill/7003576 to your computer and use it in GitHub Desktop.
Try to understand how to use `spread` in Q - a tool to compose asynchronous promises.
var Q = require('q');
var util = require('util');
function randomDelayedCall(func) {
var delay = Math.floor(Math.random() * (1200 - 100) + 100);
setTimeout(func, delay);
}
function findUser(id, cb) {
var err = null;
// err = new Error('Cannot find the user with id: ' + id);
var name = 'Kate';
if (0 === id % 2) {
name = 'Bob';
}
randomDelayedCall(function() {
cb(err, name);
});
}
function jsonify(name, cb) {
var jsonString = '{"name": "' + name + '"}';
var result = JSON.parse(jsonString);
var err = null;
randomDelayedCall(function() {
cb(err, result);
});
}
function sendResult(jsonData, cb) {
var err = null;
// err = new Error('Cannot send result!');
randomDelayedCall(function() {
console.log('Result:', util.inspect(jsonData));
cb(err);
});
}
function save(name, cb) {
var err = null;
randomDelayedCall(function() {
console.log('Saved to DB.');
cb(err);
});
}
// Q.nfcall(findUser, 4)
// .then(function(name) {
// console.log('Found user:', name);
// return Q.nfcall(save, name).then(function() {
// return Q.nfcall(jsonify, name);
// });
// })
// .then(function(jsonData) {
// return Q.nfcall(sendResult, jsonData);
// })
// .then(function() {
// console.log('Finished');
// })
// .fail(function(error) {
// console.error('Error occurred: ', error);
// });
/* by using spread, get the same result as above */
Q.nfcall(findUser, 5)
.then(function(name) {
console.log('Found user:', name);
return [name, Q.nfcall(jsonify, name)];
})
.spread(function(name, jsonData) {
return [Q.nfcall(save, name), Q.nfcall(sendResult, jsonData)];
})
.spread(function() {
console.log('Finished.');
})
.fail(function(error) {
console.error(error);
});
// Call done() if you don't have a failed handler,
// the errors will be thrown to outside.
// Otherwise, the errors are swallowed.
// .done();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment