GitXplorerGitXplorer
l

promise-cookbook

public
2 stars
2 forks
0 issues

Commits

List of commits on branch master.
Unverified
9c7d72f202a65e6be71e77dbb5f1d9300e75c0dc

Promise.resolve Promise.reject

lluoyjx committed 8 years ago
Unverified
57b82250ed21dc791b143d27308686f65553b6dc

Promise.race

lluoyjx committed 8 years ago
Unverified
f70a00a668d2fe26f36502c4ed7f34b5b37d9944

merge

lluoyjx committed 8 years ago
Unverified
3fe9a1eca79386726c86ac858eae75412231fd58

add Promise.all implementation

lluoyjx committed 8 years ago
Unverified
e4f9a0c9bc21580e962fd053da8e3d184c73ccc9

fix typo

committed 8 years ago
Unverified
29033c484ecf05f1ed84620183c88c9503a133b6

p0实现promise实例化过程

committed 8 years ago

README

The README file for this repository.

promise-cookbook

learn how to cook promise

Promise 标准描述

标准中规定:

  1. Promise对象初始状态为 Pending,在被 resolvereject 时,状态变为 FulfilledRejected
  2. resolve接收成功的数据,reject接收失败或错误的数据
  3. Promise对象必须有一个 then 方法,且只接受两个可函数参数 onFulfilledonRejected

then方法

标准中规定:

  1. then 方法必须返回一个新的 Promise实例(ES6中的标准,Promise/A+中没有明确说明)
  2. 为了保证 then中回调的执行顺序,onFulfilledonRejected 必须异步调用

扩展方法实现

Promise.all

Promise.all = function(iterable){
  var _this = this;
  return new this(function(resolve, reject){
    if(!iterable || !Array.isArray(iterable)) return reject( new TypeError('must be an array') );
    var len = iterable.length;
    if(!len) return resolve([]);
    var res = Array(len), counter = 0, called=false;
    iterable.forEach(function(v, i){
      (function(i){
        _this.resolve(v).then(function(value){
          res[i]=value;
          if(++counter===len && !called){
            called = true;
            return resolve(res)
          }
        }, function(err){
          if(!called){
            called = true;
            return reject(err);
          }
        })
      })(i)
    })
  })
}

Promise.race

用于并行执行promise组成的数组(数组中可以不是Promise对象, 在调用过程中会使用 Promise.resolve(value) 转换成Promise对象),如果某个promise的状态率先改变, 就获得改变的结果,返回一个新的Promise对象

Promise.race = function(iterable){
  var _this = this;
  return new this(function(resolve, reject){
    if(!iterable || !Array.isArray(iterable)) return reject( new TypeError('must be an array') );
    var len = iterable.length;
    if(!len) return resolve([]);
    var called = false;
    iterable.forEach(function(v, i){
      _this.resolve(v).then(function(res){
        if(!called){
          called = true;
          return resolve(res);
        }
      }, function(err){
        if(!called){
          called = true;
          return reject(err);
        }
      })
    })
  })
}

Promise.resolve

用于包装任意对象为promise对象,返回一个新的promise,并且状态是resolved

Promise.resolve = function(value){
  if(value instanceof this) return value;
  return executeCallback.bind(new this())('resolve', value);
}

Promise.reject

用于包装任意对象为promise对象,返回一个新的promise,并且状态是rejected

Promise.reject = function(value){
  if(value instanceof this) return value;
  return executeCallback.bind(new this())('reject', value);
}