Promise–详解
ES5之前处理异步的方法
- 会先封装一个工具函数
- 接收三个参数,业务参数,成功回调函数,失败回调函数
- 这种需要将成功以及失败的业务逻辑梳理清除,而且参数位置也没有规范
function tool(count, successCall, failCall) {
setTimeout(() => {
if (count > 0) {
//填写业务逻辑
successCall();
} else {
//填写业务逻辑
failCall();
}
}, 2000);
}
tool(
10,
() => {
//成功之后的业务逻辑
console.log("执行成功");
},
() => {
//失败之后的业务逻辑
console.log("执行失败");
}
);
引出Promise
- Promise 是一个类,因此在使用的时候,需要new Promise
- 通过 new Promise创建对象时候,我们需要在里面传递一个回调函数,称之为 executor
- 这个回调函数会立即执行,并且传入另外两个回调函数 resolve reject
function tool(count) {
//创建promise对象
const promise = new Promise((resolve, reject) => {
if (count > 0) {
//成功时候执行resolve
resolve("成功");
} else {
//失败时候执行reject
reject("失败");
}
});
//返回promise对象
return promise;
}
tool(10)
//.then接收resolve执行函数
.then((res) => {
console.log(res);
})
//.catch接收reject执行的函数
.catch((err) => {
console.log(err);
});
Promise三个状态
pending(等待),fulfilled(成功)、rejected(已拒绝)
- promise状态只会由 pending—>fufilled,或者 pending—>rejected这样转换,且转换之后的状态不会再切换
const promise = new Promise((resolve, reject) => {
console.log(123);
console.log(123);
///--以上都是pending状态
resolve("123"); //转成了fulfilled状态
resolve("adafaf");//只会执行一次改变状态的函数
reject(); //不会执行reject
console.log(123456); //但是后面的代码会执行
});
promise
.then((res) => {
console.log(res);
})
.catch((err) => {
});
- fufilled状态
- resolve函数中传递 普通值的时候:会直接返回值
- resolve函数中传递 另一个Promise对象,则当前promise状态由传入的Promise来决定
- resolve函数中传递 对象,且该对象中有then方法,则会执行该then方法,并且根据then方法的结果决定Promise的状态
//传递普通值
const promise1 = new Promise((resolve, reject) => {
resolve("123");
});
promise1.then((res) => {
console.log(res);
});
//传递另外一个promise
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(123);
}, 2000);
});
const promise2 = new Promise(