Skip to content
/ yapi.js Public

yet another Promises/A+ implementation which works in both browser and node

Notifications You must be signed in to change notification settings

loveky/yapi.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Promises/A+ logo

YAPI.js Build Status

yet another Promises/A+ implementation which works in both browser and node

Install

Bower

bower install -S yapi

NPM

npm install --save yapi

Usage

You can use two ways to create a promsie.

Option 1

Use YAPI.createPromsie method.

var promise = YAPI.createPromise(function (resolve, reject) {
  // if promise is fulfilled
  resolve();
  
  // or if promise is rejected
  reject();
});

promise.then(function () {
  // fulfilled callback
}, function () {
  // rejected callback
});

Here is an example of a simple XHR2 wrapper written using YAPI.js:

var getJSON = function(url) {
  var promise = YAPI.createPromise(function(resolve, reject){
    var client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

    function handler() {
      if (this.readyState === this.DONE) {
        if (this.status === 200) { resolve(this.response); }
        else { reject(this); }
      }
    };
  });

  return promise;
};

Check the example.html for a full demo which uses the about XHR2 wrapper.

Option 2

Manualy create a deferred object and resolve/reject it ondemand.

var getUserInfo = function () {
  var deferred = YAPI.defer();
  
  // fetch user information throught AJAX
  deferred.resolve(); // if AJAX request succeed
  // or
  deferred.reject(); // if something wrong
  
  return deferred.promise;
};

Develop

npm test # run Promises/A+ Compliance Test Suite
grunt build # jshint & generate min version

Todos

About

yet another Promises/A+ implementation which works in both browser and node

Resources

Stars

Watchers

Forks

Packages

No packages published