spoike
7/2/2013 - 10:47 AM

Async func with promise and optional callback

Async func with promise and optional 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;

// 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);