一、Promise是什么?
Promise是异步编程的一种解决方案,比传统的解决方案--回调函数和事件更合理和强大,由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Promise对象;
简单来说,Promise就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果,从语法上来说,Promise是一个对象,从它可以获取异步操作的消息,Promise提供统一的API,各种异步操作都可以用同样的方法进行处理;
Promise对象的特点:
①对象的状态不受外界影响,Promise对象代表一个异步操作,有三种状态:pending
(进行中)、fulfilled
(已成功)、rejected
(已失败),只有异步操作的结果可以决定当前是哪一种状态,任何其他操作都无法改变这个状态;
②一旦状态改变,就不会再变,任何时候都可以得到这个结果,Promise对象的状态改变,只有两种可能:从pending
变为fulfilled
和从pending
变为rejected
,只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果,这时就称为resolved(已定型),如果改变已经发生了,再对Promise对象添加回调函数,也会立即得到这个结果,这与事件(Event)完全不同,事件的特点是:如果你错过了它,再去监听,是得不到结果的;
Promise对象的优点:
①Promise对象将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数;
②Promise对象提供统一的接口,使得控制异步操作更加容易;
Promise对象的缺点:
①无法取消Promise,一旦新建它就会立即执行,无法中途取消;
②如果不设置回调函数,Promise内部抛出的错误不会反应到外部;
③当处于pending
状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成);
二、Promise对象的基本用法
Promise对象是一个构造函数,用来生成Promise实例;
// Promise实例
const promise = new Promise(function(resolve, reject) {
// ... some code
if ( /* 异步操作成功 */ ) {
resolve(value);
} else {
reject(error);
}
});
// 为Promise实例指定回调函数
promise.then(function(value) {
// success
}, function(error) {
// failure
});
Promise构造函数接受一个函数作为参数,这个函数的参数分别是resolve和reject两个函数,这两个函数由JavaScript引擎提供,不用自己部署;
resolve函数:将Promise对象的状态由“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果作为参数传递出去;
reject函数:将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去;
.then函数:将Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数;then方法可以接受两个回调函数作为参数,第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用,其中第二个函数是可选的,不一定要提供,这两个函数都接受Promise对象传出的值作为参数;
// 一个实例
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done'); // resolve后才可以执行then
});
}
timeout(100).then((value) => {
console.log(value); // done
});
// Promise 新建后就会立即执行
let promise=new Promise((resolve,reject)=>{
console.log('Promise新建后立即执行');
resolve(); // 如果没有这句,then永远不会执行
})
promise.then(()=>{
console.log('回调方法then在所有同步任务执行完后执行');
})
console.log('同步任务');
// Promise新建后立即执行
// 同步任务
// 回调方法then在所有同步任务执行完后执行
// 异步加载图片
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
const image = new Image();
image.onload = function() {
resolve(image); // 成功时resolve
};
image.onerror = function() { // 失败时reject
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});
}
// 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函数时带有参数,那么它们的参数会被传递给回调函数,reject函数的参数通常是Error对象的实例,表示抛出的错误;resolve函数的参数除了正常的值以外,还可能是另一个Promise实例;
// p1和p2都是Promise的实例,但是p2的resolve方法将p1作为参数,即一个异步操作的结果是返回另一个异步操作
// 此时p1的状态决定了p2的状态,如果p1的状态是pending,那么p2的回调函数就会等待p1的状态改变,如果p1的状态已经是resolved或者rejected,那么p2的回调函数将会立刻执行;
const p1 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('fail')), 3000)
})
const p2 = new Promise((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方法指定的回调函数;
// 调用resolve或reject并不会终结Promise的参数函数的执行,代码中,调用resolve(1)后,后面的console.log(2)还是会执行,并且会首先打印出来,
// 这是因为立即resolved的Promise是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务;
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
})
// 2
// 1
// 一般来说,调用resolve或reject以后,Promise的使命就完成了,后继操作应该放到then方法里面去,而不应该直接写在resolve或reject的后面,
// 所以最好在它们前面加上return语句,这样就不会有意外;
new Promise((resolve, reject) => {
return resolve(1);
console.log(2); // 2不会被打印
}).then(r => {
console.log(r);
})
// 1
三、Promise.prototype.then()链式调用
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(function funcA(comments) {
console.log("resolved: ", comments);
}, function funcB(err) {
console.log("rejected: ", err);
});
// 第一个then方法指定的回调函数返回的是另一个Promise对象,这时第二个then方法指定的回调函数就会等待这个新的Promise对象状态发生变化,如果变为resolved,就调用funcA,如果状态变为rejected,就调用funB;
// 箭头函数写法
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)的别名,用于指定发生错误时的回调函数;
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));
// 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);
});
// 写法二
// reject方法的作用,等同于抛出错误
const promise = new Promise(function(resolve, reject) {
reject(new Error('test'));
});
promise.catch(function(error) {
console.log(error);
});
// 如果 Promise 状态已经变成resolved,再抛出错误是无效的
// Promise 在resolve语句后面,再抛出错误,就不会再被捕获了,等于没有抛出,因为Promise的状态一旦改变,就永远保持该状态,不会再变了
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
// Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止,
// 也就是说,错误总是会被下一个catch语句捕获
// 三个 Promise 对象:一个由getJSON产生,两个由then产生,任何一个抛出的错误,都会被最后一个catch捕获
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 处理前面三个Promise产生的错误
});
// 不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),总是使用catch方法
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
// 可以捕获前面then方法执行中的错误,也更接近同步的写法(try/catch),因此,建议总是使用catch方法,而不使用then方法的第二个参数
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
// 如果没有使用catch方法指定错误处理的回调函数,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);
// Promise 内部的错误不会影响到 Promise 外部的代码,即“Promise 会吃掉错误”
// Uncaught (in promise) ReferenceError: x is not defined
// 123
// 代码中Promise指定下一轮“事件循环”再抛出错误,到了那个时候,Promise的运行已经结束了,所以这个错误在Promise函数体外抛出的,会冒泡到最外层,成了未捕获的错误;
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
// 运行完catch方法指定的回调函数,会接着运行后面then方法指定的回调函数,如果没有报错,则会跳过catch方法
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
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]
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为y没有声明
y + 2;
}).catch(function(error) { // 第二个catch方法用来捕获前一个catch方法抛出的错误
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
五、Promise.prototype.finally()
finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作;
// 不管promise最后的状态,在执行完then或catch指定的回调函数以后,都会执行finally方法指定的回调函数
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
// 然后使用finally方法关掉服务器
server.listen(port)
.then(function () {
// ...
})
.finally(server.stop);
// finally本质上是then方法的特例
// finally方法的回调函数不接受任何参数,这意味着没有办法知道,前面的 Promise 状态到底是fulfilled还是rejected。这表明,finally方法里面的操作,应该是与状态无关的,不依赖于 Promise 的执行结果
promise
.finally(() => {
// 语句
});
// 等同于
promise
.then(
result => {
// 语句
return result;
},
error => {
// 语句
throw error;
}
);
// 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 })
);
};
// 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.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例
// p1、p2、p3都是 Promise 实例,如果不是,就会先调用Promise.resolve方法,将参数转为 Promise 实例,再进一步处理;
// 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数;
// 只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数
const p = Promise.all([p1, p2, p3]);
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) {
// ...
});
// p2有自己的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会resolve,p2首先会rejected,但是p2有自己的catch方法,该方法返回的是一个新的Promise实例,p2指向的实际上是这个实例,该实例执行完catch方法后,也会变成resolved,导致Promise.all()方法参数里面的两个实例都会resolved,因此会调用then方法指定的回调函数,而不会调用catch方法指定的回调函数;
// 如果p2没有自己的catch方法,就会调用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()
// 只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变,那个率先改变的 Promise 实例的返回值,就传递给p的回调函数;
const p = Promise.race([p1, p2, p3]);
// 如果5秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数
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.resolve()
// 将现有对象转为 Promise 对象
Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
- 如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例;
- thenable对象
// thenable对象指的是具有then方法的对象
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
// Promise.resolve方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then方法
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
console.log(value); // 42
});
- 如果参数是一个原始值,或者是一个不具有then方法的对象,则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved
// 返回 Promise 实例的状态从一生成就是resolved,所以回调函数会立即执行
const p = Promise.resolve('Hello');
p.then(function (s){
console.log(s)
});
// Hello
- 不带有任何参数
// Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的 Promise 对象
const p = Promise.resolve();
p.then(function () {
// ...
});
// 立即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()
// 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.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致
十、Promise.try()
// Promise.try就是模拟try代码块,就像promise.catch模拟的是catch代码块
try {
database.users.get({id: userId})
.then(...)
.catch(...)
} catch (e) {
// ...
}
十一、Promise链式调用
// 采用链式的then,可以指定一组按照次序调用的回调函数
function start() {
return new Promise((resolve, reject) => {
resolve('start');
});
}
start()
.then(data => {
// promise start
console.log('result of start: ', data);
return Promise.resolve(1); // p1
})
.then(data => {
// promise p1
console.log('result of p1: ', data);
return Promise.reject(2); // p2
})
.then(data => {
// promise p2
console.log('result of p2: ', data);
return Promise.resolve(3); // p3
})
.catch(ex => {
// promise p3
console.log('ex: ', ex);
return Promise.resolve(4); // p4
})
.then(data => {
// promise p4
console.log('result of p4: ', data);
});
// 最终结果
result of start: start
result of p1: 1
ex: 2
result of p4: 4
总结:代码的执行逻辑是 promise start --> promise p1 --> promise p3 --> promise p4,所以结合输出结果总结出以下几点:
- promise 的 then 方法里面可以继续返回一个新的 promise 对象;
- 下一个 then 方法的参数是上一个 promise 对象的 resolve 参数;
- catch 方法的参数是其之前某个 promise 对象的 rejecte 参数;
- 一旦某个 then 方法里面的 promise 状态改变为了 rejected,则promise 方法会连跳过后面的 then 直接执行 catch;
- catch 方法里面依旧可以返回一个新的 promise 对象;
function p1() {
return new Promise((resolve) => {
console.log(1);
resolve();
});
}
function p2() {
return new Promise((resolve) => {
console.log(2);
resolve();
});
}
function p3() {
return new Promise((resolve) => {
console.log(3);
resolve();
});
}
p1()
.then(() => {
return p2();
})
.then(() => {
return p3();
})
.then(() => {
console.log('all done');
})
.catch(e => {
console.log('e: ', e);
});
// 输出结果:
// 1
// 2
// 3
// all done
p1()
.then(() => {
return Promise.all([
p2(),
p3(),
]);
})
.then(() => {
console.log('all done');
})
.catch((e) => {
console.log('e: ', e);
});
// 或者
Promise.all([p1(),p3(),p3()]).then(function(data){console.log(data)})
// 输出结果:
// 1
// 2
// 3
// all done
参考:
Promise 对象