Promise 的含义
1.Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。
所谓Promise
,简单说就是一个容器,里面保存着某个未来才会结束的事件,通常是一个异步操作的结果。
从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。
2.对象的状态不受外界影响。
Promise
对象代表一个异步操作,有三种状态:pending
(进行中)、fulfilled
(已成功)和rejected
(已失败)。
只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。
3.一旦状态改变,就不会再变,任何时候都可以得到这个结果。
Promise
对象的状态改变,只有两种可能:从pending
变为fulfilled
和从pending
变为rejected
。
只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果,这时就称为 resolved(已定型)。
如果改变已经发生了,你再对Promise
对象添加回调函数,也会立即得到这个结果。
这与事件(Event)完全不同,事件的特点是,如果你错过了它,再去监听,是得不到结果的。
4.有了Promise
对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。
此外,Promise
对象提供统一的接口,使得控制异步操作更加容易。
5.Promise
也有一些缺点。
首先,无法取消Promise
,一旦新建它就会立即执行,无法中途取消。
其次,如果不设置回调函数,Promise
内部抛出的错误,不会反应到外部。
第三,当处于pending
状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。
基本用法
const promise = new Promise(function(resolve, reject) { ... if (异步操作成功) { resolve(); } else { reject(error); } });
1.ES6 规定,Promise
对象是一个构造函数,用来生成Promise
实例。
Promise
构造函数接受一个函数作为参数,该函数的两个参数分别是resolve
和reject
。(构造函数的参数)
它们是两个函数,由 JavaScript 引擎提供,不用自己部署。
2.resolve
函数的作用是,将Promise
对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;
reject
函数的作用是,将Promise
对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
promise.then(function(value) { // success }, function(error) { // failure });
3.Promise
实例生成以后,可以用then
方法分别指定resolved
状态和rejected
状态的回调函数。
then
方法可以接受两个回调函数作为参数。(实例then方法的参数)
第一个回调函数是Promise
对象的状态变为resolved
时调用,第二个回调函数是Promise
对象的状态变为rejected
时调用。
其中,第二个函数是可选的,不一定要提供。
这两个函数都接受Promise
对象传出的值作为参数。
function timeout(ms) { return new Promise(function(resolve, reject) { return setTimeout(resolve, ms, 'done'); }); } timeout(100).then(function(vaule) { return console.log(value); // done });
4.上面代码中,timeout
方法返回一个Promise
实例,表示一段时间以后才会发生的结果。
过了指定的时间(ms
参数)以后,Promise
实例的状态变为resolved
,就会触发then
方法绑定的回调函数。
let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!'); // Promise // Hi! // resolved
5.Promise 新建后就会立即执行。
上面代码中,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; // 赋值图片地址 }); }
6.异步加载图片。
const getJSON = function(url) { const promise = new Promise(function(resolve, reject) { const handler = function() { // 处理函数 if (this.readyState !== 4) { return; } if (this.status === 2000) { 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; // 结果都在这个promise里 } getJSON('/posts.json').then(function(json) { console.log('Contents: ' + json); }, function(error) { console.log('出错了', error); });
7.一个用Promise
对象实现的 Ajax 操作的例子。
const p1 = new Promise(function (resolve, reject) { // ... }); const p2 = new Promise(function (resolve, reject) { // ... resolve(p1); })
8.resolve
函数的参数除了正常的值以外,还可能是另一个 Promise 实例。
new Promise((resolve, reject) => { resolve(1); console.log(2); }).then(r => { console.log(r); }); // 2 // 1
9.注意,调用resolve
或reject
并不会终结 Promise 的参数函数的执行。
上面代码中,调用resolve(1)
以后,后面的console.log(2)
还是会执行,并且会首先打印出来。
这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务。
new Promise((resolve, reject) => { return resolve(1); // 后面的语句不会执行 console.log(2); })
10.一般来说,调用resolve
或reject
以后,Promise 的使命就完成了,后继操作应该放到then
方法里面,而不应该直接写在resolve
或reject
的后面。
所以,最好在它们前面加上return
语句,这样就不会有意外。
Promise.prototype.then()
1.Promise 实例具有then
方法,也就是说,then
方法是定义在原型对象Promise.prototype
上的。
它的作用是为 Promise 实例添加状态改变时的回调函数。
then
方法的第一个参数是resolved
状态的回调函数,第二个参数(可选)是rejected
状态的回调函数。
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... });
2.then
方法返回的是一个新的Promise
实例(注意,不是原来那个Promise
实例)。
因此可以采用链式写法,即then
方法后面再调用另一个then
方法。
上面的代码使用then
方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
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); });
3.采用链式的then
,可以指定一组按照次序调用的回调函数。
这时,前一个回调函数,有可能返回的还是一个Promise
对象(即有异步操作),这时后一个回调函数,就会等待该Promise
对象的状态发生变化,才会被调用。
上面代码中,第一个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) );
4.箭头函数版
Promise.prototype.catch()
getJSON('/posts.json').then(function(posts) { // ... }).catch(function(error) { // 处理 getJSON 和 前一个回调函数运行时发生的错误 console.log('发生错误!', error); });
1.Promise.prototype.catch
方法是.then(null, rejection)
的别名,用于指定发生错误时的回调函数。
上面代码中,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
2.上面代码中,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); });
3.比较上面两种写法,可以发现reject
方法的作用,等同于抛出错误。
const 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
4.如果 Promise 状态已经变成resolved
,再抛出错误是无效的。
上面代码中,Promise 在resolve
语句后面,再抛出错误,不会被捕获,等于没有抛出。
因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。
getJSON('/post/1.json').then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // some code }).catch(function(error) { // 处理前面三个Promise产生的错误 });
5.Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。
也就是说,错误总是会被下一个catch
语句捕获。
// bad promise .then(function(data) { // success }, function(err) { // error }); // good promise .then(function(data) { //cb // success }) .catch(function(err) { // error });
6.一般来说,不要在then
方法里面定义 Reject 状态的回调函数(即then
的第二个参数),总是使用catch
方法。
上面代码中,第二种写法要好于第一种写法,理由是第二种写法可以捕获前面then
方法执行中的错误,也更接近同步的写法(try/catch
)。
因此,建议总是使用catch
方法,而不使用then
方法的第二个参数。
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
7.跟传统的try/catch
代码块不同的是,如果没有使用catch
方法指定错误处理的回调函数,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
8.一般总是建议,Promise 对象后面要跟catch
方法,这样可以处理 Promise 内部发生的错误。
catch
方法返回的还是一个 Promise 对象,因此后面还可以接着调用then
方法。
上面代码运行完catch
方法指定的回调函数,会接着运行后面那个then
方法指定的回调函数。
如果没有报错,则会跳过catch
方法。
Promise.resolve() .catch(function(error) { console.log('oh no', error); }) .then(function() { console.log('carry on'); }); // carry on
9.上面的代码因为没有报错,跳过了catch
方法,直接执行后面的then
方法。
此时,要是then
方法里面报错,就与前面的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]
10.catch
方法之中,还能再抛出错误。
上面代码中,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]
Promise.prototype.finally()
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
1.finally
方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。
上面代码中,不管promise
最后的状态,在执行完then
或catch
指定的回调函数以后,都会执行finally
方法指定的回调函数。
server.listen(port) .then(function () { // ... }) .finally(server.stop);
2.一个例子,服务器使用 Promise 处理请求,然后使用finally
方法关掉服务器。
finally
方法的回调函数不接受任何参数,这意味着没有办法知道,前面的 Promise 状态到底是fulfilled
还是rejected
。
这表明,finally
方法里面的操作,应该是与状态无关的,不依赖于 Promise 的执行结果。
promise .finally(() => { // 语句 }); // 等同于 promise .then( result => { // 语句 return result; }, error => { // 语句 throw error; } );
3.finally
本质上是then
方法的特例。
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 }) ); };
4.它的实现也很简单。
// resolve 的值是 undefined Promise.resolve(2).then(() => {}, () => {}) // resolve 的值是 2 Promise.resolve(2).finally(() => {}) // reject 的值是 undefined Promise.reject(3).then(() => {}, () => {}) // reject 的值是 3 Promise.reject(3).finally(() => {})
5.finally
方法总是会返回原来的值。
Promise.all()
const p = Promise.all([p1, p2, p3]);
1.Promise.all
方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
2.p
的状态由p1
、p2
、p3
决定,分成两种情况。
(1)只有p1
、p2
、p3
的状态都变成fulfilled
,p
的状态才会变成fulfilled
,此时p1
、p2
、p3
的返回值组成一个数组,传递给p
的回调函数。
(2)只要p1
、p2
、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){ // ... });
3.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));
4.booksPromise
和userPromise
是两个异步操作,只有等到它们的结果都返回了,才会触发pickTopRecommentations
这个回调函数。
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: 报错了]
5.如果作为参数的 Promise 实例,自己定义了catch
方法,那么它一旦被rejected
,并不会触发Promise.all()
的catch
方法。
上面代码中,p1
会resolved
,p2
首先会rejected
,但是p2
有自己的catch
方法,该方法返回的是一个新的 Promise 实例,p2
指向的实际上是这个实例。
该实例执行完catch
方法后,也会变成resolved
,导致Promise.all()
方法参数里面的两个实例都会resolved
,因此会调用then
方法指定的回调函数,而不会调用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: 报错了
6.如果p2
没有自己的catch
方法,就会调用Promise.all()
的catch
方法。
Promise.race()
const p = Promise.race([p1, p2, p3]);
1.Promise.race
方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。
上面代码中,只要p1
、p2
、p3
之中有一个实例率先改变状态,p
的状态就跟着改变。
那个率先改变的 Promise 实例的返回值,就传递给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(console.log) .catch(console.error);
2.如果指定时间内没有获得结果,就将 Promise 的状态变为reject
,否则变为resolve
。
上面代码中,如果 5 秒之内fetch
方法无法返回结果,变量p
的状态就会变为rejected
,从而触发catch
方法指定的回调函数。
Promise.resolve()
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
1.有时需要将现有对象转为 Promise 对象,Promise.resolve
方法就起到这个作用。
上面代码将 jQuery 生成的deferred
对象,转为一个新的 Promise 对象。
Promise.resolve('foo') // 等价于 new Promise(resolve => resolve('foo'))
2.Promise.resolve
等价的写法。
3.Promise.resolve
方法的参数分成四种情况。
(1)参数是一个 Promise 实例
如果参数是 Promise 实例,那么Promise.resolve
将不做任何修改、原封不动地返回这个实例。
let thenable = { then: function(resolve, reject) { resolve(42); } };
let thenable = { then: function(resolve, reject) { resolve(42); } }; let p1 = Promise.resolve(thenable); p1.then(function(value) { console.log(value); // 42 });
(2)参数是一个thenable
对象
thenable
对象指的是具有then
方法的对象,比如下面这个对象。
Promise.resolve
方法会将这个对象转为 Promise 对象,然后就立即执行thenable
对象的then
方法。
const p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
(3)参数不是具有then
方法的对象,或根本就不是对象
如果参数是一个原始值,或者是一个不具有then
方法的对象,则Promise.resolve
方法返回一个新的 Promise 对象,状态为resolved
。
上面代码生成一个新的 Promise 对象的实例p
。由于字符串Hello
不属于异步操作(判断方法是字符串对象不具有 then 方法),返回 Promise 实例的状态从一生成就是resolved
,所以回调函数会立即执行。Promise.resolve
方法的参数,会同时传给回调函数。
const p = Promise.resolve(); p.then(function () { // ... });
(4)不带有任何参数
Promise.resolve
方法允许调用时不带参数,直接返回一个resolved
状态的 Promise 对象。
所以,如果希望得到一个 Promise 对象,比较方便的方法就是直接调用Promise.resolve
方法。
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one // two // three
5.需要注意的是,立即resolve
的 Promise 对象,是在本轮“事件循环”(event loop)的结束时,而不是在下一轮“事件循环”的开始时。
上面代码中,setTimeout(fn, 0)
在下一轮“事件循环”开始时执行,Promise.resolve()
在本轮“事件循环”结束时执行,console.log('one')
则是立即执行,因此最先输出。
Promise.reject()
const p = Promise.reject('出错了'); // 等同于 const p = new Promise((resolve, reject) => reject('出错了')) p.then(null, function (s) { console.log(s) }); // 出错了
1.Promise.reject(reason)
方法也会返回一个新的 Promise 实例,该实例的状态为rejected
。
上面代码生成一个 Promise 对象的实例p
,状态为rejected
,回调函数会立即执行。
const thenable = { then(resolve, reject) { reject('出错了'); } }; Promise.reject(thenable) .catch(e => { console.log(e === thenable) }) // true
2.注意,Promise.reject()
方法的参数,会原封不动地作为reject
的理由,变成后续方法的参数。
这一点与Promise.resolve
方法不一致。
上面代码中,Promise.reject
方法的参数是一个thenable
对象,执行以后,后面catch
方法的参数不是reject
抛出的“出错了”这个字符串,而是thenable
对象。
应用
const preloadImage = function (path) { return new Promise(function (resolve, reject) { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = path; }); };
1.我们可以将图片的加载写成一个Promise
,一旦加载完成,Promise
的状态就发生变化。
function getFoo () { return new Promise(function (resolve, reject){ resolve('foo'); }); } const g = function* () { try { const foo = yield getFoo(); console.log(foo); } catch (e) { console.log(e); } }; function run (generator) { const it = generator(); function go(result) { if (result.done) return result.value; return result.value.then(function (value) { return go(it.next(value)); }, function (error) { return go(it.throw(error)); }); } go(it.next()); } run(g);
2.使用 Generator 函数管理流程,遇到异步操作的时候,通常返回一个Promise
对象。
上面代码的 Generator 函数g
之中,有一个异步操作getFoo
,它返回的就是一个Promise
对象。函数run
用来处理这个Promise
对象,并调用下一个next
方法。
Promise.try()
Promise.resolve().then(f)
1.实际开发中,经常遇到一种情况:不知道或者不想区分,函数f
是同步函数还是异步操作,但是想用 Promise 来处理它。
因为这样就可以不管f
是否包含异步操作,都用then
方法指定下一步流程,用catch
方法处理f
抛出的错误。
const f = () => console.log('now'); Promise.resolve().then(f); console.log('next'); // next // now
2.上面代码中,函数f
是同步的,但是用 Promise 包装了以后,就变成异步执行了。
const f = () => console.log('now'); (async () => f())(); console.log('next'); // now // next
3.那么有没有一种方法,让同步函数同步执行,异步函数异步执行,并且让它们具有统一的 API 呢?
回答是可以的,并且还有两种写法。
第一种写法是用async
函数来写。
上面代码中,第二行是一个立即执行的匿名函数,会立即执行里面的async
函数,因此如果f
是同步的,就会得到同步的结果;如果f
是异步的,就可以用then
指定下一步,就像下面的写法。
(async () => f())() .then(...) .catch(...)
4.需要注意的是,async () => f()
会吃掉f()
抛出的错误。所以,如果想捕获错误,要使用promise.catch
方法。
const f = () => console.log('now'); ( () => new Promise( resolve => resolve(f()) ) )(); console.log('next'); // now // next
5.第二种写法是使用new Promise()
。
上面代码也是使用立即执行的匿名函数,执行new Promise()
。这种情况下,同步函数也是同步执行的。