Rect-Native 中针对 Promise的理解和探索
$[timeformat('2017-12-22T09:21:42+08:00')]

概念理解

icon
icon

所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。

Promise 状态

  • Pending 进行中
  • Resolved 已完成 又称Fulfilled
  • Rejected 已失败

Promise 特点

  • 对象的状态不受外部因素影响。Promise对象代表的是一个异步操作,只有异步操作的结果能决定Promise的状态,任何其他操作都不能决定其状态。
  • 一旦Promise有了结果状态就不会再变。Pending==>Resolved,或者Pending==>Rejected

Promise 缺点

Promise的缺点是:一旦建立就会立即执行,无法中途取消。

Promise 基本用法

var promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

Promise对象接受一个参数,这个参数是一个函数体。 这个函数有两个参数:一个是resolve,一个是reject。这两个参数是Promise自动提供,不需要使用者传值。

  • resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 Pending 变为 Resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去
  • reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 Pending 变为 Rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。 Promise实例生成后,可以用then分别指定Resolved和Rejected的回调函数。
promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

then方法会接受两个参数:

  • 第一个函数,Promise状态变更为Resolved时调用。
  • 第二个函数,Promise状态变为Rejected时调用。可选的,可以不提供。

下面是异步加载图片的例子:

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    var image = new Image();

    image.onload = function() {
      resolve(image);
    };

    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };

    image.src = url;
  });
}

下面是Promise实现的Ajax操作的例子:

var getJSON = function(url) {
  var promise = new Promise(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 !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出错了', error);
});

注意:在getJSON内部,resolve函数和reject函数调用时,都带有参数!!
如果调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给回调函数。

  • reject函数的参数通常是Error对象的实例,表示抛出的错误
  • resolve函数的参数除了正常的值以外,还可能是另一个 Promise 实例,表示异步操作的结果有可能是一个值,也有可能是另一个异步操作
var p1 = new Promise(function (resolve, reject) {
  // ...
});

var p2 = new Promise(function (resolve, reject) {
  // ...
  resolve(p1);
})

上面👆,p1p2 都是Promise,但是p2的resolve把p1作为返回值参数传出去了,即一个异步操作的返回结果是另一个异步操作。(类似于iOS开发中的自动布局库 Masonry,可以无限点语法取到对象)。
注意:此时,p1的状态会传递p2.如果p1是Pending状态,那么p2会等待p1的结果。如果p1是Reject或者Resolve状态,那么p2的回调函数将会立即执行。

再看:

var p1 = new Promise(function (resolve, reject) {
  setTimeout(() => reject(new Error('fail')), 3000)
})

var p2 = new Promise(function (resolve, reject) {
  setTimeout(() => resolve(p1), 1000)
})

p2.then(result => console.log(result))
  .catch(error => console.log(error))
// Error: fail
  1. p1会在3秒后抛出error。
  2. p2会在1秒后改变状态。Resolv的返回值是p1.
  3. 由于p2的返回值是一个Promise,导致p2自己的状态无效了,此时p2的状态取决于p1.
  4. 所以,后面的then语句,都变成针对p1的了。
  5. 又过了2秒p1变为reject,导致触发catch方法。

3. Promise.prototype.then()

then方法是定义在原型对象Promise.prototype上的。 作用:为Promise对象添加状态改变时的回调函数。第一个是Resolved,第二个是Rejected。 then方法返回的是一个新的Promise对象,不是之前的实例。因此 then方法后面还可以再写一个then方法,即链式调用。

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});

第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function funcA(comments) {
  console.log("Resolved: ", comments);
}, function funcB(err){
  console.log("Rejected: ", err);
});

第一个then函数返回的是一个新的Promise对象。于是才能继续调用then方法。 第二个then方法指定的回调函数,就会等待这个Promise对象状态发生变化,resolv会调用funcA,reject会调用funcB.

下面👇是箭头函数的实现,会更简洁:

getJSON("/post/1.json").then(
  post => getJSON(post.commentURL)
).then(
  comments => console.log("Resolved: ", comments),
  err => console.log("Rejected: ", err)
);

4. Promise.prototype.catch()

Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数

Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数.

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 处理 getJSON 和 前一个回调函数运行时发生的错误
  console.log('发生错误!', error);
});

getJSON()方法返回的是一个Promise对象。如果resolv,会调用then方法;如果reject则会调用catch方法。

then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获

另外,then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获

p.then((val) => console.log('fulfilled:', val))
  .catch((err) => console.log('rejected', err));

// 等同于
p.then((val) => console.log('fulfilled:', val))
  .then(null, (err) => console.log("rejected:", err));
var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error);
});
// Error: test

Promise对象Resolved,但是Resolved指定的方法跑出错误。 Promise对象catch方法能捕获跑出的error。

reject方法等同于抛出错误

上面的写法跟下面的两种写法是一样的:

// 写法一
var promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) {
    reject(e);
  }
});
promise.catch(function(error) {
  console.log(error);
});

// 写法二
var promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});

由此可见:reject方法等同于抛出错误。

resolve之后在抛出错误,catch是捕获不到的不到的。

var promise = new Promise(function(resolve, reject) {
  resolve('ok');
  throw new Error('test');
});
promise
  .then(function(value) { console.log(value) })
  .catch(function(error) { console.log(error) });
// ok

resolve之后在抛出错误,catch是捕获不到的不到的。

Promise 对象的错误具有“冒泡”性质

Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止 ------ 错误总是会被下一个catch语句捕获

举个栗子:就像是Y染色体上受环境触发的遗传疾病,会不断的遗传给男性后代,任意一个男性都会被特殊的环境触发。

getJSON('/post/1.json').then(function(post) {
  return getJSON(post.commentURL);
}).then(function(comments) {
  // some code
}).catch(function(error) {
  // 处理前面三个Promise产生的错误
});

上述代码中有三个Promise,第一个由getJSON产生,后两个由then产生。他们之中的任何一个抛出错误,都会被catch捕获。

一般来讲,尽量不要定义Promise的reject状态的回调函数,最好总是使用catch函数,因为catch函数不仅能捕获到reject状态,还能捕获到resolve状态指定方法下抛出的异常。

Promise对象抛出的错误不会传递到外层代码

如果没有使用catch方法指定错误处理的回调函数,Promise对象抛出的错误不会传递到外层代码,即不会有任何反应,这一点上跟传统的try/catch代码块不同的。

process.on('unhandledRejection', function (err, p) {
  console.error(err.stack)
});

时间的监听函数‘unhandledRejection’,有两个参数: 第一个是错误对象 第二个是报错的Promise实例

catch方法返回的也是一个Promise实例,所以后面还是可以无限的调用then方法。 如果catch函数在几个then中间,二执行过程中都没有reject状态,那么会跳过这个中间的catch方法。

catch方法中也能抛出错误

var someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // 下面一行会报错,因为x没有声明
    resolve(x + 2);
  });
};

someAsyncThing().then(function() {
  return someOtherAsyncThing();
}).catch(function(error) {
  console.log('oh no', error);
  // 下面一行会报错,因为y没有声明
  y + 2;
}).then(function() {
  console.log('carry on');
});
// oh no [ReferenceError: x is not defined]

如上:catch方法指定的函数依旧是可以抛出Error的,但是因为后面没有继续跟进catch方法,所以并没有被捕获。

5. Promise.all()

Promise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。

var p = Promise.all([p1, p2, p3]);

Promise.all方法接受一个数组作为参数,p1、p2、p3都是 Promise 实例,如果不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。 (Promise.all方法的参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。)

p的状态由p1、p2、p3决定,分成两种情况:

  • 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数
  • 只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数

注意,如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result)
.catch(e => e);

const p2 = new Promise((resolve, reject) => {
  throw new Error('报错了');
})
.then(result => result)
.catch(e => e);

Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 报错了]

p1会resolved,p2首先会rejected. p2有自己的catch方法,并且执行了,那么就会返回一个新的Promise,并且这个Promise的状态会变成Resolved。 所以:Promise.all()的catch方法并不能捕获到这个error。 p2没有自己的catch方法,所以会调用Promise.all()的catch方法。

6. Promise.race()

Promise.race方法同样是将多个Promise实例,包装成一个新的Promise实例。

var p = Promise.race([p1, p2, p3]);

p1/p2/p3中只要有一个率先改变状态,p的状态就会随着改变。那个率先改变状态的实例的返回值,就会传递给p的回调函数。

const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)
  })
]);
p.then(response => console.log(response));
p.catch(error => console.log(error));

5秒内无法返回请求结果,变量p的状态就会变为reject。这也算是竞速的一种应用场景。

7. Promise.resolve()

有时需要将现有对象转为Promise对象,Promise.resolve方法就起到这个作用.

var jsPromise = Promise.resolve($.ajax('/whatever.json'));

等价于下面的说法:

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))

Promise 的第一个参数是一个箭头函数,函数的传入参数是resolve(函数),函数体就是调用传入的函数resolve,resolve调用的时候,也需要一个参数,此时这个参数就是咱们需要转变成Promise对象的那个参数。

Promise.resolve的参数有四种情况:

  1. 参数是一个Promise实例
  2. 参数是一个thenable对象(有then方法的实例)
  3. 参数是不具备then方法d的对象应该
  4. 不带参数,返回一个Resolved的返回状态。

8、Promise.reject() 同上

9、两个常用附加方法

done()

Promise的错误并不会冒泡到全局,所以我们可以提供一个done方法总是处于会吊链的尾端。

asyncFunc()
  .then(f1)
  .catch(r1)
  .then(f2)
  .done();

done方法的使用,可以像then方法那样用,提供Fulfilled和Rejected状态的回调函数,也可以不提供任何参数。但不管怎样,done都会捕捉到任何可能出现的错误,并向全局抛出.

finally()

finally方法用于指定不管Promise对象最后状态如何,都会执行的操作。它与done方法的最大区别,它接受一个普通的回调函数作为参数,该函数不管怎样都必须执行。

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value  => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

Promis.try()

try {
  database.users.get({id: userId})
  .then(...)
  .catch(...)
} catch (e) {
  // ...
}
Promise.try(database.users.get({id: userId}))
  .then(...)
  .catch(...)

Promise.try就是模拟try代码块,就像promise.catch模拟的是catch代码块.