Created
October 31, 2013 23:42
-
-
Save cer/7258999 to your computer and use it in GitHub Desktop.
An example of a function that returns a promise and takes a callback
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
var when = require("when"); | |
function makePromiseCallback(label, callback) { | |
var deferred = when.defer(); | |
function actualCallback(err, data) { | |
if (err) | |
console.log(label || "some label", {err: err, data: data}); | |
if (err) | |
deferred.reject(err); | |
else | |
deferred.resolve(data); | |
callback && callback(err, data); | |
} | |
return {promise: deferred.promise, callback: actualCallback}; | |
} | |
function longRunningOperation(n, callback) { | |
var pc = makePromiseCallback("longRunningOperation", callback); | |
setTimeout(function () { pc.callback(undefined, n * n)}, 1000 ); | |
return pc.promise; | |
} | |
exports.longRunningOperation = longRunningOperation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment