Skip to content

Instantly share code, notes, and snippets.

@alemures
Last active April 20, 2016 15:35
Show Gist options
  • Save alemures/6020eedacc49e5bc2ec902974f221040 to your computer and use it in GitHub Desktop.
Save alemures/6020eedacc49e5bc2ec902974f221040 to your computer and use it in GitHub Desktop.
Comparison between different ways to implement async methods in Node.js
'use strict';
const async = require('async');
const Promise = require('bluebird');
const db = {
app: [
{ id: 10, name: 'twitter' },
{ id: 11, name: 'facebook' },
{ id: 12, name: 'google' }
],
user: [
{ id: 20, name: 'Alejandro', age: 24 },
{ id: 21, name: 'James', age: 26 },
{ id: 22, name: 'Kevin', age: 28 }
],
_indexes: {
app: {
10: 0,
11: 1,
12: 2
},
user: {
20: 0,
21: 1,
22: 2
}
}
};
const APP_ID = 10;
const USER_ID = 20;
// Async functions using promises and callbacks
function getApp(id) {
return new Promise((resolve, reject) => {
var index = db._indexes.app[id];
setTimeout(_ => {
if (index !== undefined) {
resolve(db.app[index]);
} else {
reject(new Error('App not found'));
}
}, 50);
});
}
function getUser(id) {
return new Promise((resolve, reject) => {
var index = db._indexes.user[id];
setTimeout(_ => {
if (index !== undefined) {
resolve(db.user[index]);
} else {
reject(new Error('User not found'));
}
}, 50);
});
}
function getAppCb(id, cb) {
var index = db._indexes.app[id];
setTimeout(_ => {
if (index !== undefined) {
cb(null, db.app[index]);
} else {
cb(new Error('App not found'));
}
}, 50);
}
function getUserCb(id, cb) {
var index = db._indexes.user[id];
setTimeout(_ => {
if (index !== undefined) {
cb(null, db.user[index]);
} else {
cb(new Error('User not found'));
}
}, 50);
}
// Async code handlers
var coroutine = Promise.coroutine(function* () {
try {
var app = yield getApp(APP_ID);
var user = yield getUser(USER_ID);
console.log('coroutine:', app, user);
} catch(e) {
console.error('coroutine:', e);
}
});
function promises() {
getApp(APP_ID).then(app => {
getUser(USER_ID).then(user => {
console.log('promises:', app, user);
}).catch(err => console.error('promises:', err));
}).catch(err => console.error('promises:', err));
}
function callbacks() {
getAppCb(APP_ID, (err, app) => {
if (err) { console.error('callbacks:', err); return; }
getUserCb(USER_ID, (err, user) => {
if (err) { console.error('callbacks:', err); return; }
console.log('callbacks:', app, user);
});
});
}
function asyncSeries() {
async.series({
app: cb => getAppCb(APP_ID, cb),
user: cb => getUserCb(USER_ID, cb)
}, (err, result) => {
if (err) { console.error('asyncSeries:', err); return; }
console.log('asyncSeries:', result.app, result.user);
});
}
coroutine();
promises();
callbacks();
asyncSeries();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment