用途:是为了解决回调地狱的问题
promise有两个重要的属性:状态和结果,
promise状态分为三个pending,fulfilled、rejected。其中只能pending变为fulfilled或者rejected,其状态是不可逆
promise的状态是由promise内接受的两个函数决定的reslove()和reject(),如果成功就会去调用reslove()函数pending也会变为fulfilled,其中reslove内的参数也就是结果会传递下去比如在then方法中传递。如果失败就会去调用rejected()函数pending也会变为rejected。rejected中的参数也就是失败的原因
代码案例:
let promise = new Promise(function(resolve, reject) {
// 异步操作
setTimeout(function() {
if (/* 异步操作成功 */) {
resolve('Success');
// 将状态改为fulfilled,并传递结果
} else {
reject(new Error('Failure'));
// 将状态改为rejected,并传递错误信息
} }, 2000);
});
promise中最常用的方法是then,其返回的是一个新的promis对象,then中同样接受两个函数,onFulfilled, onRejected,第一个是如果前一个promise是成功的状态则执行第一个函数,如果是失败则去执行第二个函数,如果是pending则两个都不执行,这也就意味着链式then只要前面有一个失败则后面then都不会去执行了,然后promise的状态并不一定要reslove和reject去操作,在then中return 则状态会变为fulfilled,如果其中有代码出错则会pending变为rejected
代码演示:
asyncFunc().then(function(result) {
console.log(result); // Success
}, function(error) {
console.error(error); // Failure
});
promise中的catch方法等同于then中的(null,onrejected)是用来捕获错误的
代码演示:
asyncFunc().catch(function(error) {
console.error(error); // Failure
});
promise中的finally()方法是用于注册最终的回调函数,无论promise的状态是什么都会去执行,一般用于清理操作
promise.finally(function() {
console.log('Finally'); // 无论成功还是失败,都会执行
});
promise中all()方法,它是接受几个promise对象同时处理,当几个对象处理完,如果几个对象都是fulfilled状态那么返回的新的promise对象也是fulfilled,并且它的值是一个数组promise,里面是一个状态和几个值,如果几个对象中只要有一个是rejected状态,那么它就会也是rejected状态和返回的reason
代码演示:
var promise1 = Promise.resolve('Promise 1');
var promise2 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Promise 2');
}, 2000); });
var promise3 = fetch('https://api.example.com/data'); // 假设fetch返回一个Promise对象 Promise.all([promise1, promise2, promise3]) .then(function(results) {
console.log(results); // [ 'Promise 1', 'Promise 2', response ]
}) .catch(function(error) {
console.error(error); // 处理错误
});
promise中的allsetted()方法,它的 要求是只要传进去的promise对象都不是pending就行了,不管是fulfilled还是rejected都可以,然后它返回的是一个promise对象数组,里面包含状态和结果
promise中的race()方法,它和它的英文名有点想,比赛的意思,同时接受几个promise对象,谁先转化状态,那么它返回的新promise就是谁