Skip to content

Instantly share code, notes, and snippets.

@boutros
Forked from isaacs/callbacksarehard.js
Created September 24, 2012 09:49
Show Gist options
  • Save boutros/3775195 to your computer and use it in GitHub Desktop.
Save boutros/3775195 to your computer and use it in GitHub Desktop.
let's go shopping!
// before
mainWindow.menu("File", function(err, file) {
if(err) throw err;
file.openMenu(function(err, menu) {
if(err) throw err;
menu.item("Open", function(err, item) {
if(err) throw err;
item.click(function(err) {
if(err) throw err;
mainWindow.getChild(type('Window'), function(err, dialog) {
if(err) throw err;
...
});
});
});
});
});
// using named functions
function doSomething (cb) {
mainWindow.menu("File", onFile)
function onFile (er, file) {
if (er) return cb(er)
file.openMenu(onMenu)
}
function onMenu (er, menu) {
if (er) return cb(er)
menu.item("Open", onOpen)
}
function onOpen (er, item) {
if (er) return cb(er)
item.click(onClick)
}
function onClick (er) {
if (er) return cb(er)
mainWindow.getChild(type("Window"), onGetWindow)
}
function onGetWindow (er, dialog) {
if (er) return cb(er)
// i presume this is where it ends?
dialog.doSomething(cb)
}
}
// this looks like:
// a(cb) --> b(results, cb) --> c(results, cb) ...
// Just a first-pass off-the-cuff flow control abstraction.
// You can do much better than this!
function passAlong () {
var cb = Array.prototype.pop.call(arguments)
, steps = Array.prototype.slice.call(arguments)
n()
function n (er) {
if (er) return cb(er)
var next = steps.shift()
if (!next) cb.apply(null, arguments)
else next.apply(null, Array.prototype.slice.call(arguments).concat(n))
}
}
function doSomething (cb) {
passAlong
(function (cb) { mainWindow.menu("file", cb) }
,function (file, cb) { file.openMenu(cb) }
,function (menu, cb) { menu.item("Open", cb) }
,function (item, cb) { item.click(cb) }
,function (cb) { mainWindow.getChild(type("Window"), cb) }
,function (dialog, cb) { dialog.doSomething(cb) }
,cb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment