异步编程解决方案——Promise对象(ES6语法)

JavaScript异步编程的六种方案

  • 回调函数
  • 事件监听
  • 事件发布/订阅模式
  • Promise
  • 生成器Generators/ yield
  • async/await

JS 异步编程进化史:callback -> promise -> generator -> async/await编程

Promise对象

Promise是什么

promise即承诺,异步编程的一种解决方式,内部保存异步操做,经过它能够得到异步操做的消息json

特色数组

  • 对象的状态不受外部影响。总共三种状态,进行中pending、已成功fulfilled、已失败rejected。只有异步操做的结果,能够决定当前是哪种状态,任何其余操做都没法改变这个状态。
  • 一旦状态改变,就不会再变,任什么时候候均可以获得这个结果。状态改变只有两种可能:从pending变为fulfilled和从pending变为rejected。状态凝固后,被称为resolved已定型。

优势:接口统一,使得控制异步操做方便;解决回调地狱,将异步操做以同步操做的流程表现出来promise

缺点:中途没法取消,一旦新建就当即执行;内部报错没法反应到外部(无回调函数的话);pending状态是没法知道具体执行到哪一步bash

new Promise(请求1)
    .then(请求2(请求结果1))
    .then(请求3(请求结果2))
    .then(请求4(请求结果3))
    .then(请求5(请求结果4))
    .catch(处理异常(异常信息))
复制代码

基本用法

第一步,建立Promise实例app

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

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

resolve()将pending状态变为resolved状态,同时传出参数(通常是异步操做返回的结果)
reject()将pending状态变为rejected状态,同时传出参数(通常是错误信息)
复制代码

第二步,指定回调函数异步

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

then方法能够接受两个回调函数做为参数。
第一个回调函数是Promise对象的状态变为resolved时调用,
第二个回调函数是Promise对象的状态变为rejected时调用。
复制代码

Promise 新建后当即执行async

Promise内部建立的代码当即执行,回调函数放入任务队列中,调用栈中的任务(即同步任务)都执行完才执行任务队列中的任务。异步编程

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('resolved.');
});

console.log('Hi!');

输出以下:
// Promise
// Hi!
// resolved
复制代码

通常Promise都以函数返回的形式来建立,好处是封装后在不一样场合下能够屡次使用函数

用Promise对象实现的 Ajax 操做

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

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

resolve()reject()参数是另外一个Promise实例时,原Promise状态失效,由新Promise的状态决定原Promise的回调函数执行

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

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

p2
  .then(result => console.log(result))
  .catch(error => console.log(error))
// Error: fail

分析以下:
p1三秒后进入rejected状态,p2一秒后进入resolved状态
因为p2的参数为p1,则一秒后,p2状态失效,由p1决定p2的状态
此时p1仍处于pending状态
两秒后,p1状态变为rejected,则p2状态也变为rejected
触发回调函数.catch(),打印出p1的reject()中的参数
复制代码

调用resolve或reject并不会终结 Promise 的参数函数的执行

new Promise((resolve, reject) => {
  resolve(1);
  console.log(2);
}).then(r => {
  console.log(r);
});
// 2
// 1
复制代码

在前面加个return就会终结了

new Promise((resolve, reject) => {
  return resolve(1);
  // 后面的语句不会执行
  console.log(2);
})
复制代码

Promise.prototype

Promise.prototype.then()

参数

第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。

返回值

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。

所以能够采用链式写法,即then方法后面再调用另外一个then方法。

链式操做

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

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});
复制代码

前一个回调函数,返回的是一个Promise对象(即有异步操做),后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。

getJSON("/post/1.json").then(
  post => getJSON(post.commentURL)
).then(
  comments => console.log("resolved: ", comments),
  err => console.log("rejected: ", err)
);
复制代码

Promise.prototype.catch()

Promise.prototype.catch等价于.then(null, rejection).then(undefined, rejection)

建议用.catch()而不用.then()的第二个参数来捕获错误

由于.catch()不只能够处理Promise对象状态变成rejected,还能捕获.then()方法中的错误

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

若是 Promise 状态已经变成resolved,再抛出错误是无效的

Promise 对象的错误具备“冒泡”性质,会一直向后传递,直到被捕获为止

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

Promise 会吃掉错误

Promise的定义若是有语法错误,控制台会显示,可是代码不会中止运行,会继续执行,即Promise 内部的错误不会影响到 Promise 外部的代码

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

someAsyncThing().then(function() {
  console.log('everything is great');
});

setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123
复制代码

返回值也是一个Promise对象,能够链式操做

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

someAsyncThing()
.catch(function(error) {
  console.log('oh no', error);
})
.then(function() {
  console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on

若是没有报错,则会跳过catch方法
复制代码

Promise.prototype.finally()

finally方法用于指定无论 Promise 对象最后状态如何,都会执行的操做。

在执行完then或catch指定的回调函数之后,也还会执行finally方法指定的回调函数。

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
复制代码

回调函数不接受任何参数

没法判断状态,就是为了少写相同的代码(then和catch中都要写的)

实现

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 })
  );
};
复制代码

返回值老是原来的值

// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})
// resolve 的值是 2
Promise.resolve(2).finally(() => {})

// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})
// reject 的值是 3
Promise.reject(3).finally(() => {})
复制代码

Promise方法

Promise.all()

做用:将多个 Promise 实例,包装成一个新的 Promise 实例

语法const p = Promise.all([p1, p2, p3]);

参数:输入一个数组,数组元素若不是Promise 实例,则会被Promise.resolve转成实例

返回值:返回一个新的Promise 实例,p的状态由p一、p二、p3决定

  • 只有p一、p二、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p一、p二、p3的返回值组成一个数组,传递给p的回调函数。
  • 只要p一、p二、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
  • 若是做为参数的 Promise 实例,本身定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

总结:逻辑与,全fulfilledfulfilled,一rejectedrejected

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: 报错了]
复制代码

Promise.race()

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

上面代码中,只要p一、p二、p3之中有一个实例率先改变状态,p的状态就跟着改变。

那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

总结:竞赛,谁先返回就返回该值

// 若是指定时间内没有得到结果,就将 Promise 的状态变为reject,不然变为resolve。
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(console.log)
.catch(console.error);
复制代码

Promise.allSettled()

只有等到全部这些参数实例都返回结果,不论是fulfilled仍是rejected,包装实例才会结束。

返回的新的 Promise 实例,一旦结束,状态老是fulfilled

总结:都被设置,能解决Promise.all()的没法知道全部操做都结束

const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);

const allSettledPromise = Promise.allSettled([resolved, rejected]);

allSettledPromise.then(function (results) {
  console.log(results);
});
// [
//    { status: 'fulfilled', value: 42 },
//    { status: 'rejected', reason: -1 }
// ]
复制代码

监听函数接收到的参数是数组results。

该数组的每一个成员都是一个对象,对应传入Promise.allSettled()的两个 Promise 实例。

每一个对象都有status属性,该属性的值只多是字符串fulfilled或字符串rejected。

fulfilled时,对象有value属性,rejected时有reason属性,对应两种状态的返回值。

Promise.any()

Promise.any()方法接受一组 Promise 实例做为参数,包装成一个新的 Promise 实例。

只要参数实例有一个变成fulfilled状态,包装实例就会变成fulfilled状态;若是全部参数实例都变成rejected状态,包装实例就会变成rejected状态。

总结:逻辑或,一fulfilledfulfilled,全rejectedrejected

var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);
var alsoRejected = Promise.reject(Infinity);

Promise.any([resolved, rejected, alsoRejected]).then(function (result) {
  console.log(result); // 42
});

Promise.any([rejected, alsoRejected]).catch(function (results) {
  console.log(results); // [-1, Infinity]
});
复制代码

Promise.resolve()

做用:将现有对象转为 Promise 对象

语法

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
复制代码

参数

(1)参数是一个 Promise 实例

Promise.resolve将不作任何修改、原封不动地返回这个实例。

(2)参数是一个thenable对象

Promise.resolve方法会将这个对象转为 Promise 对象,而后就当即执行thenable对象的then方法。

let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
};

let p1 = Promise.resolve(thenable);
p1.then(function(value) {
  console.log(value);  // 42
});
复制代码

(3)参数不是具备then方法的对象,或根本就不是对象

Promise.resolve方法返回一个新的 Promise 对象,状态为resolved,回调函数的参数就是该参数。

const p = Promise.resolve('Hello');

p.then(function (s){
  console.log(s)
});
// Hello
复制代码

(4)不带有任何参数

直接返回一个resolved状态的 Promise 对象。就是要注意回调执行的顺序。

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');

// one
// two
// three
复制代码

Promise.reject()

返回一个新的 Promise 实例,该实例的状态为rejected。

Promise.reject()方法的参数,会原封不动地做为reject的理由,变成后续方法的参数。

const p = Promise.reject('出错了');
// 等同于
const p = new Promise((resolve, reject) => reject('出错了'))

p.then(null, function (s) {
  console.log(s)
});
// 出错了
复制代码

Promise.try()

让同步函数同步执行,异步函数异步执行,而且让它们具备统一的 API

如下的函数f()表示的是不肯定是同步或者异步的操做

// 方法一:
const f = () => console.log('now');
(
  () => new Promise(
    resolve => resolve(f())
  )
)();
console.log('next');
// now
// next
复制代码
// 方法二:
(async () => f())()
.then(...)
.catch(...)
复制代码
// 方法三:
Promise.try(() => f())
  .then(...)
  .catch(...)
复制代码
相关文章
相关标签/搜索