Promise 对象——异步操作解决方案

参考来源:
ruanyifeng
es6-ruanyifeng

概述

  • Promise 对象是 JavaScript 的异步操作解决方案,为异步操作提供统一接口。
  • Promise 是一个对象,也是一个构造函数。
  • Promise 使得本需嵌套的回调函数写法(串行)变成了链式写法
//回调函数f1
function f1(resolve, reject) {
  // 异步代码...
}
var p1 = new Promise(f1); //返回一个 Promise 实例
p1.then(f2); //then方法,指定下一个执行的回调函数f2。

Promise 对象的状态

Promise 实例具有三种状态:

异步操作未完成(pending)
异步操作成功(fulfilled)
异步操作失败(rejected)

Promise 的最终结果只有两种:

异步操作成功,Promise 实例传回一个值(value),状态变为fulfilled。
异步操作失败,Promise 实例抛出一个错误(error),状态变为rejected。

Promise.prototype.then()

  • 用来添加回调函数
  • 接受两个回调函数,第一个是异步操作成功时(变为fulfilled状态)时的回调函数,第二个是异步操作失败(变为rejected)时的回调函数(该参数可以省略)。
  • 成功时的回调函数console.log,失败时的回调函数console.error
// Promise构造函数接受一个函数作为参数
// resolve和reject是JavaScript 引擎提供的两个函数
// resolve函数将Promise实例的状态从“未完成”变为“成功”,并将异步操作的结果,作为参数传递出去。
// reject函数将Promise实例的状态从“未完成”变为“失败”,并将异步操作的结果,作为参数传递出去。
var p1 = new Promise(function (resolve, reject) {
  resolve('成功');
});
p1.then(console.log, console.error);
// "成功"

var p2 = new Promise(function (resolve, reject) {
  reject(new Error('失败'));
});
p2.then(console.log, console.error);
// Error: 失败

then方法可以链式使用:

// 只要前一步的状态变为fulfilled,就会依次执行紧跟在后面的回调函数
p1
  .then(step1)
  .then(step2)
  .then(step3)
  .then(
    console.log,
    console.error
  );

猜你喜欢

转载自blog.csdn.net/ee2222/article/details/80260037