Promise的出现
Promise是异步操作的一种解决方案,有时候我们使用回调函数异步操作时会层层嵌套,不利于我们修改需求。Promise一般用来解决层层嵌套的回调函数(回调地狱 callback hell)的问题。
Promise的基本用法
第一步:实例化Promise构造函数
const p = new Promise((resolve,reject)=>{}) //Promise解决的不是回调函数,而是回调地狱.
resolve和reject是函数,调用它们可以改变Promise的状态。
promise的回调函数在实例化时就会执行。在回调函数中调用resolve或reject来改变promise的状态
第二步:Promise的三个状态
pending:初始态,未完成或等待;
执行resolve()后变成fulfilled(别名resolved):已成功
执行reject()变成rejected状态:已失败
注意:Promise的状态一旦变化,就不会再改变了(只能变第一次)
第三:Promise的then方法
then方法中有两个回调函数作为参数,如果Promise的状态为fulfilled则执行第一个回调函数;如果状态为rejected则执行第二个回调函数
例: p.then(()=>{},()=>{})
调用resolve改变状态时,传递的参数会作为then方法的第一个回调函数的参数;调用reject改变状态时,传递的参数会作为then方法的第二个回调函数的参数
一般reject(new Error('reason'))
then方法什么时候执行:
当Promise的状态由pending->fulfilled的时候执行第一个回调函数;当Promise的状态由pending->rejected的时候执行第二个回调函数;
then方法执行后的返回值是一个新的Promise对象:
<script>
//查看p.then()的返回值
const p = new Promise((resolve,reject) =>{
resolve();
}) //Promise的状态由pending变为filfilled
const p2 = p.then(
() => {}, //执行第一个回调函数
() => {}
).then().then() //返回的是一个Promise对象,也有then方法
console.log(p2); //Promise
console.log(p2 == p); //false
</script>
then方法返回的Promise对象的状态改变:看调用这个then方法的状态,默认状态是fulfilled,如果想要rejected状态则需手动修改:
<script>
const p = new Promise((resolve,reject) =>{
console.log("我调用了reslove,所以我是filfilled状态")
resolve();
}) //Promise的状态由pending变为filfilled
//默认情况下,Promise调用then方法生成的Promise的状态:
const p2 = p.then(
(data) =>{
console.log("调用我的Promise没有改变我的状态,所以我也是默认状态")
console.log(data); // Undefined
return(111);
},
() => {}
).then(
(data) => {
console.log("调用我的Promise没有改变我的状态,所以我也是默认状态");
console.log(data); // 111
return new Promise((resolve,reject)=>{
// 使用默认状态
resolve(123);//默认调用resolve,状态为filfilled
})
},
() => {}
).then(
(data) => {
console.log("调用我的promise的调用等同于默认状态,所以我是默认状态,但我调用then生成的Promise不使用默认状态");
console.log(data);// 123
//调用then生成的Promise不使用默认的状态,则需自己写完整调用过程
return new Promise((resolve,reject) =>{
reject(new Error('reason'))
})
},
() => {}
).then(
() => {},
(data)=>{
console.log("我是非默认状态");
console.log(data); // Error
}
)
</script>