Skip to content

Instantly share code, notes, and snippets.

@cer
Created October 31, 2013 23:42
Show Gist options
  • Save cer/7258999 to your computer and use it in GitHub Desktop.
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
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