Promise定义
Promise:一个对象,是异步操作的一种处理方案,主要解决了回调地狱callback hell问题。
Promise将处理程序与异步操作的最终成功值或失败原因关联起来,让异步方法像同步方法一样返回值,但不是立即返回最终值,异步方法返回一个Promise,在将来的某个时候提供该值。
Promise对象有三种状态:
- pending:进行中
- resolved:完成
- rejected:失败
Promise只有两种状态变化:(创建Promise时,PromiseStatus将处于pending状态)变化是不可逆的。
- pending ——> resolved
- pending ——> rejected
Promise构造函数语法:
new Promise(function(resolve, reject){
})
构造函数接收一个函数作为参数,在该函数中,包含两个参数resolve和reject,也都是函数。
Promise对象的静态方法:
- Promise.resolve(value):返回一个新的Promise对象,该对象将实现给定值,将Promise对象的状态从pending改为resolved,resolved状态会触发后续then的回调。
- Promise.reject(reason):返回一个新的Promise对象,该对象以给定的错误原因被拒绝,将Promise对象的状态从pending改为rejected,rejected状态后续会触发catch的回调。
Promise对象的原型方法:
- Promise.prototype.catch()
- Promise.prototype.then()
- Promise.prototype.finally()
then和catch改变Promise状态:
- then正常返回resolved状态,里面有报错则返回rejected状态
- catch正常返回resolved状态,里面有报错则返回rejected状态
示例1:
var p1 = Promise.resolve().then(() => {
return 100;
}) //resolved状态
console.log(p1);
p1.then(() => {
console.log("p1");
}).catch(() => {
console.log("p1 error");
})
var p2 = Promise.resolve().then(() => {
throw new Error('error');
}) //rejected状态
console.log(p2);
p2.then(() => {
console.log("p2");
}).catch(() => {
console.log("p2 error");
})
因此,then正常返回resolved状态,里面有报错则返回rejected状态,resolved状态会触发后续then的回调,rejected状态后续会触发catch的回调。
示例2:
var p3 = Promise.resolve().catch(() => {
console.error(err);
}) //注意,此处是resolved状态!!
console.log(p3);
p3.then(() => {
console.log("p3");
}).catch(() => {
console.log("p3 error");
})
注意:
此处正常返回,p3是resolved状态,resolved状态会触发后续then的回调,所以触发的是then方法!!
var p4 = Promise.resolve().then(() => {
throw new Error('error');
}) //rejected状态
console.log(p4);
p4.then(() => {
console.log("p4");
}).catch(() => {
console.log("p4 error");
})
因此,catch同then一样,正常返回resolved状态,里面有报错则返回rejected状态,resolved状态会触发后续then的回调,rejected状态后续会触发catch的回调。
应用于Promise关于then和catch的面试题
Promise.resolve().then(() => {
console.log(1); // resolved状态,触发then
}).catch(() => {
console.log(2);
}).then(() => {
console.log(3);
});
// 1 3
Promise.resolve().then(() => {
console.log(1);
throw new Error('error1'); // rejected状态,触发catch
}).catch(() => {
console.log(2); // resolved状态,触发then
}).then(() => {
console.log(3);
});
// 1 2 3
Promise.resolve().then(() => {
console.log(1);
throw new Error('error1'); // rejected状态,触发catch
}).catch(() => {
console.log(2); // resolved状态,触发then
}).catch(() => {
console.log(3);
});
// 1 2