Skip to content
shaohua edited this page Aug 17, 2013 · 5 revisions

101

http://blog.danielpecos.com/2013/01/javascript-promises-101/

Q

https://github.com/kriskowal/q

var fs = require('fs');
var Q = require('Q');

var read = function(){

  var deferred = Q.defer();
  fs.readFile("foo.txt", "utf-8", function (error, text) {
      if (error) {
          deferred.reject(new Error(error));
      } else {
          deferred.resolve(text);
      }
  });
  return deferred.promise;

};

var my_function = function(){
  var file_content = read();
  file_content.then(function(data){
    console.log("Data in my_function", data);
  }, function(error){
    console.log('Error in my_function', error);
  });

  file_content.finally(function(){
    console.log('Finally!');
  });
};

my_function();

The jQuery promises

http://api.jquery.com/category/deferred-object/

Clone this wiki locally