Created
November 24, 2013 07:14
-
-
Save junosuarez/7624300 to your computer and use it in GitHub Desktop.
This file contains 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
// deferred example from https://github.com/cujojs/when/blob/master/docs/api.md#nodefncreatecallback | |
var when, nodefn; | |
when = require("when"); | |
nodefn = require("when/node/function"); | |
function nodeStyleAsyncFunction(callback) { | |
if(Math.random() * 2 > 1) { | |
callback("Oh no!"); | |
} else { | |
callback(null, "Interesting value"); | |
} | |
} | |
var deferred = when.defer(); | |
nodeStyleAsyncFunction(nodefn.createCallback(deferred.resolver)); | |
deferred.promise.then(function(interestingValue) { | |
console.log(interestingValue) | |
},function(err) { | |
console.error(err) | |
}); |
This file contains 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
// using DOM Promise constructor with resolver interface | |
function nodeStyleAsyncFunction(callback) { | |
if (Math.random() * 2 > 1) { | |
callback(new Error('Oh no!')) | |
} else { | |
callback(null, 'Interesting value') | |
} | |
} | |
new Promise(function (resolve, reject) { | |
nodeStyleAsyncFunction(function (err, val) { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(val) | |
} | |
}) | |
}).then(function (interestingValue) { | |
console.log(interestingValue) | |
}, function (err) { | |
console.error(err) | |
}) |
This file contains 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
// generic node promise wrapper using DOM Promise constructor | |
function nodeStyleAsyncFunction(callback) { | |
if (Math.random() * 2 > 1) { | |
callback(new Error('Oh no!')) | |
} else { | |
callback(null, 'Interesting value') | |
} | |
} | |
function wrap(fn) { | |
return function () { | |
var args = Array.prototype.slice.call(arguments) | |
return new Promise(function (resolve, reject) { | |
var callback = function (err, val) { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(val) | |
} | |
} | |
try { | |
fn.apply(null, args.concat(callback)) | |
} catch (e) { | |
reject(e) | |
} | |
}) | |
} | |
} | |
var regularAsyncFunction = wrap(nodeStyleAsyncFunction) | |
regularAsyncFunction().then(function (val) { | |
console.log(val) | |
}, function (err) { | |
console.error(err) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment