Skip to content

Instantly share code, notes, and snippets.

@spoike
Created July 2, 2013 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spoike/5908375 to your computer and use it in GitHub Desktop.
Save spoike/5908375 to your computer and use it in GitHub Desktop.
Async func with promise and optional callback
// Usage:
var pauseModule = require('./uselessPause');
var callback = function(str) {
console.log(str);
};
// Either call the async function with callback
pauseModule(callback);
// Or call the async and queue the callback to the returned promise
pauseModule().then(callback);
// Using Q library from https://github.com/kriskowal/q
var Q = require('q');
var myAsyncFunc = function (callback) {
// Create a deferred (with Q)
var deferred = q.deferred();
// optional callback is queued into the promise
if (callback) deferred.promise.then(callback);
// Do the "async" operation and resolve when done
window.setTimeout(function() {
deferred.resolve("resolved");
}, 1000);
// Return the promise while waiting for
// the async operation to happen
return deferred.promise;
};
module.exports = myAsyncFunc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment