Promise

Promise简介  

  Promise是ES6新增类,用来解决异步的回调地狱问题,为异步提供更强大的性能支持,一个promise实例对象会存在三种状态,分别是pedding,fulfilled,rejected。创建实例的时候需要给Promise类传入一个回调函数,该回调函数可以传入两个参数,两个参数是两个函数,分别是resolve,reject函数。当触发resolve函数之后,promise的状态值变成fulfilled,之后会执行promise实例的then函数;当触发reject函数之后,promise的状态值会变成rejected,之后会执行promise实例的catch函数。

常见用法

const promise1 = new Promise((resolve, reject) => {
    // resolve();
    reject();
});

promise1.then(() => {
    console.log("触发then函数")
}).catch(() => {
    console.log("触发catch函数")
})

常用方法

then函数

当promise的状态从pedding变为fulfilled,会触发then函数,then函数接收一个函数作为参数,可以接收resolve函数传递过来的参数。

catch函数

当promise的状态从pedding变成rejected,会触发catch函数,catch函数也接收一个函数作为参数,可以接收reject函数传递过来的参数。

all函数

Promise.all([promise1, promise2]).then(() => {
    console.log("触发then函数");
}).catch(() => {
    console.log("触发catch函数");
})

race函数

Promise.race([promise1, promise2]).then(() => {
    console.log("触发then函数");
}).catch(() => {
    console.log("触发catch函数");
})