本文我是在学习阮一峰老师的ECMAScript 6 入门的Promise章节时,为了加深记忆,通篇都是照抄原文的。
原文地址:阮一峰ECMAScipt入门es6
(1)Promise对象表明一个异步操做,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操做的结果,能够决定当前是哪种状态,任何其余操做都没法改变这个状态。
(2)一旦状态改变,就不会再变,任什么时候候均可以获得这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。只要这两种状况发生,状态就凝固了,不会再变了,会一直保持这个结果,这时就称为 resolved(已定型)。若是改变已经发生了,你再对Promise对象添加回调函数,也会当即获得这个结果。这与事件(Event)彻底不一样,事件的特色是,若是你错过了它,再去监听,是得不到结果的。
有了Promise对象,就能够将异步操做以同步操做的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操做更加容易。ajax
Promise也有一些缺点。首先,没法取消Promise,一旦新建它就会当即执行,没法中途取消。其次,若是不设置回调函数,Promise内部抛出的错误,不会反应到外部。第三,当处于pending状态时,没法得知目前进展到哪个阶段(刚刚开始仍是即将完成)。json
ES6 规定,Promise对象是一个构造函数,用来生成Promise实例数组
// 下面代码创造了一个promise实例 const promise = new Promise(function(resolve, reject) { // ...some code if (/*异步操做成功*/) { resolve(value); } else { reject(error) } });
Promise构造函数接受一个函数做为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由JavaScript 引擎提供,不用本身部署。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时调用。其中,第二个函数是可选的,不必定要提供。这两个函数都接受Promise对象传出的值做为参数。app
下面是一个promise对象的简单例子:异步
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms, 'done') }); } timeout().then((value) => { console.log(value); })
上面代码中,timeout方法返回一个Promise实例,表示一段时间之后才会发生的结果。过了指定的时间(ms参数)之后,Promise实例的状态变为resolved,就会触发then方法绑定的回调函数。函数
Promise 新建后就会当即执行。
let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!');
上面代码中,promise 新建后当即执行,因此首先输出的是Promise。而后,then方法指定的回调函数,将在当前脚本全部同步任务执行完后才会执行,因此resolved最后输出。
下面是异步图片加载的例子:
function loadImageAsync(url) { return new Promise(function (resolve, reject) { const image = new Image(); image.onload = function () { resolve(image); }; image.onerror = function() { reject(new Error('Could not load image at' + url)); } image.src= url; }) }
上面代码中,使用Promise包装了一个图片加载的异步操做。若是加载成功,就调用resolve方法,不然就调用reject方法。
下面是一个用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)); } }; }); return promise; }; 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.log('出错了', error); })
上面代码中,getJSON是对 XMLHttpRequest 对象的封装,用于发出一个针对 JSON 数据的 HTTP 请求,而且返回一个Promise对象。须要注意的是,在getJSON内部,resolve函数和reject函数调用时,都带有参数。
若是调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给回调函数。reject函数的参数一般是Error对象的实例,表示抛出的错误;resolve函数的参数除了正常的值之外,还多是另外一个 Promise 实例,好比像下面这样。
const p1 = new Promise(function (resolve, reject) { // ... }); const p2 = new Promise(function (resolve, reject) { // ... resolve(p1); })
上面代码中,p1和p2都是 Promise 的实例,可是p2的resolve方法将p1做为参数,即一个异步操做的结果是返回另外一个异步操做。
注意,这时p1的状态就会传递给p2,也就是说,p1的状态决定了p2的状态。若是p1的状态是pending,那么p2的回调函数就会等待p1的状态改变;若是p1的状态已是resolved或者rejected,那么p2的回调函数将会马上执行。
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是一个 Promise,3 秒以后变为rejected。p2的状态在 1 秒以后改变,resolve方法返回的是p1。因为p2返回的是另外一个 Promise,致使p2本身的状态无效了,由p1的状态决定p2的状态。因此,后面的then语句都变成针对后者(p1)。又过了 2 秒,p1变为rejected,致使触发catch方法指定的回调函数。
附上本身的理解:p2的状态在一秒后变为resolve它的参数是p1,因此p2的状态由p1决定,p1状态此时是pending,它在三秒后状态变为rejected,则p2状态为rejected,因此触发了catch方法指定的回调函数而不是then方法的。
注意,调用resolve或reject并不会终结 Promise 的参数函数的执行。
new Promise((resolve, reject) => { resolve(1); console.log(2); }).then(r => { console.log(r); }); // 2 // 1
上面代码中,调用resolve(1)之后,后面的console.log(2)仍是会执行,而且会首先打印出来。这是由于当即 resolved 的 Promise 是在本轮事件循环的末尾执行,老是晚于本轮循环的同步任务。
通常来讲,调用resolve或reject之后,Promise 的使命就完成了,后继操做应该放到then方法里面,而不该该直接写在resolve或reject的后面。因此,最好在它们前面加上return语句,这样就不会有意外。
new Promise((resolve, reject) => { return resolve(1); // 后面的语句不会执行 console.log(2); })
Promise 实例具备then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的做用是为 Promise 实例添加状态改变时的回调函数。前面说过,then方法的第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。所以能够采用链式写法,即then方法后面再调用另外一个then方法。
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... });
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成之后,会将返回结果做为参数,传入第二个回调函数。
采用链式的then,能够指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的仍是一个Promise对象(即有异步操做),这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。
getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(functon funcA(comments) { console.log("resolved:", comments); }, function funcB(err){ console.log("rejected:", err); })
上面代码中,第一个then方法指定的回调函数,返回的是另外一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。若是变为resolved,就调用funcA,若是状态变为rejected,就调用funcB。
若是采用箭头函数,上面的代码能够写得更简洁。
getJSON("/post/1.json").then( post => getJSON(post.commentURL) ).then( comments => console.log("resolved:", comments), err => console.log("rejected:", err) );
Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。
getJSON('/posts.json').then(function(posts) { // ... }).catch(function(error) { // 处理 getJSON 和 前一个回调函数运行时发生的错误 console.log('发生错误!', error); });
上面代码中,getJSON方法返回一个 Promise 对象,若是该对象状态变为resolved,则会调用then方法指定的回调函数;若是异步操做抛出错误,状态就会变为rejected,就会调用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));
下面是一个例子
const promise = new Promise(function(resolve, reject) { throw new Error('test'); }); promise.catch(function(error) { console.log(error); }); // Error: test
上面代码中,promise抛出一个错误,就被catch方法指定的回调函数捕获。注意,上面的写法与下面两种写法是等价的。
// 写法一 const promise = new Promise(function(resolve, reject) { try { throw new Error('test'); } catch(e) { reject(e); } }); promise.catch(function(error) { console.log(error); }); // 写法二 const promise = new Promise(function(resolve, reject) { reject(new Error('test')); }); promise.catch(function(error) { console.log(error); });
比较上面两种写法,能够发现reject方法的做用,等同于抛出错误。
若是 Promise 状态已经变成resolved,再抛出错误是无效的。
const promise = new promise(function(resolve, reject) { resolve("ok"); }); promise .then((value) => console.log(value) ) .catch((error) => console.log(error) ); // ok
上面代码中,Promise 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。由于 Promise 的状态一旦改变,就永久保持该状态,不会再变了。
Promise 对象的错误具备“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误老是会被下一个catch语句捕获。
getJSON('/post/1.json').then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // some code }).catch(function(error) { // 处理前面三个Promise产生的错误 });
上面代码中,一共有三个 Promise 对象:一个由getJSON产生,两个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。
通常来讲,不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),老是使用catch方法。
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
上面代码中,someAsyncThing函数产生的 Promise 对象,内部有语法错误。浏览器运行到这一行,会打印出错误提示ReferenceError: x is not defined,可是不会退出进程、终止脚本执行,2 秒以后仍是会输出123。这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,通俗的说法就是“Promise 会吃掉错误”。
这个脚本放在服务器执行,退出码就是0(即表示执行成功)。不过,Node 有一个unhandledRejection事件,专门监听未捕获的reject错误,上面的脚本会触发这个事件的监听函数,能够在监听函数里面抛出错误。
process.on('unhandledRejection', function (err, p) { throw err; });
上面代码中,unhandledRejection事件的监听函数有两个参数,第一个是错误对象,第二个是报错的 Promise 实例,它能够用来了解发生错误的环境信息。
注意,Node 有计划在将来废除unhandledRejection事件。若是 Promise 内部有未捕获的错误,会直接终止进程,而且进程的退出码不为 0。
再看下面的例子。
const promise = new Promise(function (resolve, reject) { resolve('ok'); setTimeout(function () { throw new Error('test') }, 0) }); promise.then(function (value) { console.log(value) }); // ok // Uncaught Error: test
上面代码中,Promise 指定在下一轮“事件循环”再抛出错误。到了那个时候,Promise 的运行已经结束了,因此这个错误是在 Promise 函数体外抛出的,会冒泡到最外层,成了未捕获的错误。
通常老是建议,Promise 对象后面要跟catch方法,这样能够处理 Promise 内部发生的错误。catch方法返回的仍是一个 Promise 对象,所以后面还能够接着调用then方法。
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方法指定的回调函数,会接着运行后面那个then方法指定的回调函数。若是没有报错,则会跳过catch方法。
Promise.resolve() .catch(function(error) { console.log('oh no', error); }) .then(function() { console.log('carry on'); }); // carry on
上面的代码由于没有报错,跳过了catch方法,直接执行后面的then方法。此时,要是then方法里面报错,就与前面的catch无关了。
catch方法之中,还能再抛出错误。
const 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方法抛出一个错误,由于后面没有别的catch方法了,致使这个错误不会被捕获,也不会传递到外层。若是改写一下,结果就不同了。
someAsyncThing().then(function() { return someOtherAsyncThing(); }).catch(function(error) { console.log('oh no', error); // 下面一行会报错,由于y没有声明 y + 2; }).catch(function(error) { console.log('carry on', error); }); // oh no [ReferenceError: x is not defined] // carry on [ReferenceError: y is not defined]
上面代码中,第二个catch方法用来捕获前一个catch方法抛出的错误。
finally方法用于指定无论 Promise 对象最后状态如何,都会执行的操做。该方法是 ES2018 引入标准的。
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
上面代码中,无论promise最后的状态,在执行完then或catch指定的回调函数之后,都会执行finally方法指定的回调函数。
下面是一个例子,服务器使用 Promise 处理请求,而后使用finally方法关掉服务器。
server.listen(port) .then(function () { // ... }) .finally(server.stop);
finally方法的回调函数不接受任何参数,这意味着没有办法知道,前面的 Promise 状态究竟是fulfilled仍是rejected。这代表,finally方法里面的操做,应该是与状态无关的,不依赖于 Promise 的执行结果。
finally本质上是then方法的特例。
promise .finally(() => { // 语句 }); // 等同于 promise .then( result => { // 语句 return result; }, error => { // 语句 throw error; } );
上面代码中,若是不使用finally方法,一样的语句须要为成功和失败两种状况各写一次。有了finally方法,则只须要写一次。
它的实现也很简单。
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 }) ); };
上面代码中,无论前面的 Promise 是fulfilled仍是rejected,都会执行回调函数callback。
从上面的实现还能够看到,finally方法老是会返回原来的值。
// 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.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.all([p1, p2, p3]);
上面代码中,Promise.all方法接受一个数组做为参数,p一、p二、p3都是 Promise 实例,若是不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。(Promise.all方法的参数能够不是数组,但必须具备 Iterator 接口,且返回的每一个成员都是 Promise 实例。)
p的状态由p一、p二、p3决定,分红两种状况。
(1)只有p一、p二、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p一、p二、p3的返回值组成一个数组,传递给p的回调函数。
(2)只要p一、p二、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
下面是一个具体的例子。
// 生成一个Promise对象的数组 const promises = [2, 3, 5, 7, 11, 13].map(function (id) { return getJSON('/post/' + id + ".json"); }); Promise.all(promises).then(function (posts) { // ... }).catch(function(reason){ // ... });
上面代码中,promises是包含 6 个 Promise 实例的数组,只有这 6 个实例的状态都变成fulfilled,或者其中有一个变为rejected,才会调用Promise.all方法后面的回调函数。
下面是另外一个例子。
const databasePromise = connectDatabase(); const booksPromise = databasePromise .then(findAllBooks); const userPromise = databasePromise .then(getCurrentUser); Promise.all([ booksPromise, userPromise ]) .then(([books, user]) => pickTopRecommentations(books, user));
上面代码中,booksPromise和userPromise是两个异步操做,只有等到它们的结果都返回了,才会触发pickTopRecommentations这个回调函数。
注意,若是做为参数的 Promise 实例,本身定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。
const p1 = new Promise((resolve, reject) => { resolve('hello'); }) .then(result => result); const p2 = new Promise((resolve, reject) => { throw new Error('报错了'); }) .then(result => result); Promise.all([p1, p2]) .then(result => console.log(result)) .catch(e => console.log(e)); // Error: 报错了
Promise.race方法一样是将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.race([p1, p2, p3]);
上面代码中,只要p一、p二、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
Promise.race方法的参数与Promise.all方法同样,若是不是 Promise 实例,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。
下面是一个例子,若是指定时间内没有得到结果,就将 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 对象,Promise.resolve方法就起到这个做用。
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
上面代码将 jQuery 生成的deferred对象,转为一个新的 Promise 对象。
Promise.resolve等价于下面的写法。
Promise.resolve('foo') // 等价于 new Promise(resolve => resolve('foo'))
Promise.resolve方法的参数分红四种状况。
(1)参数是一个 Promise 实例
若是参数是 Promise 实例,那么Promise.resolve将不作任何修改、原封不动地返回这个实例。
(2)参数是一个thenable对象
thenable对象指的是具备then方法的对象,好比下面这个对象。
let thenable = { then: function(resolve, reject) { resolve(42); } };
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 });
上面代码中,thenable对象的then方法执行后,对象p1的状态就变为resolved,从而当即执行最后那个then方法指定的回调函数,输出 42。
(3)参数不是具备then方法的对象,或根本就不是对象
若是参数是一个原始值,或者是一个不具备then方法的对象,则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved。
const p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
上面代码生成一个新的 Promise 对象的实例p。因为字符串Hello不属于异步操做(判断方法是字符串对象不具备 then 方法),返回 Promise 实例的状态从一辈子成就是resolved,因此回调函数会当即执行。Promise.resolve方法的参数,会同时传给回调函数。
(4)不带有任何参数
Promise.resolve方法容许调用时不带参数,直接返回一个resolved状态的 Promise 对象。
因此,若是但愿获得一个 Promise 对象,比较方便的方法就是直接调用Promise.resolve方法。
const p = Promise.resolve(); p.then(function () { // ... });
上面代码的变量p就是一个 Promise 对象。
须要注意的是,当即resolve的 Promise 对象,是在本轮“事件循环”(event loop)的结束时,而不是在下一轮“事件循环”的开始时。
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one // two // three
上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是当即执行,所以最早输出。
Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected。
const p = Promise.reject('出错了'); // 等同于 const p = new Promise((resolve, reject) => reject('出错了')) p.then(null, function (s) { console.log(s) }); // 出错了
上面代码生成一个 Promise 对象的实例p,状态为rejected,回调函数会当即执行。
注意,Promise.reject()方法的参数,会原封不动地做为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致。
const thenable = { then(resolve, reject) { reject('出错了'); } }; Promise.reject(thenable) .catch(e => { console.log(e === thenable) }) // true
上面代码中,Promise.reject方法的参数是一个thenable对象,执行之后,后面catch方法的参数不是reject抛出的“出错了”这个字符串,而是thenable对象。