Created
July 2, 2013 10:47
-
-
Save spoike/5908375 to your computer and use it in GitHub Desktop.
Async func with promise and optional 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
// 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); |
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 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