简单总结-如何理解Promise
第一点:Promise 构造函数创建完就会首先执行,是同步执行的。而.then是异步执行的执行
const pro = new Promise((resolve,reject)=>{
console.log(1);
resolve();
console.log(2)
})
pro.then(()=>{
console.log(3)
})
//1
//2
//3
const pro= new Promise((resolve,reject)=>{
console.log(1);
//resolve();
console.log(2);
reject()
})
pro.then(()=>{
console.log(3)
},()=>{ console.log(4)})
//1
//2
//4
注意:必须调用resolve或者reject 方法才会执行.then //resolve和reject都是在同级其他执行完才会执行
第二点:promise 第一次执行完,return的返回值相当于下一次.then调用传入的参数.promise链式调用,
const pro = Promise.resolve(1);
pro.then((res)=>{
console.log(res);
return 2
}).then((res)=>{
console.log(res);
return 3
}).then((res)=>{
console.log(res);
return 4
})
//1
//2
//3
第三点:promise 内部状态一经改变,并且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。即promise 的 .then 或者 .catch 可以被调用多次,但这里 Promise 构造函数只执行一次。
const pro = new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log(1);
resolve(‘sucess’);
},1000)
});
let startDate = Date.now();
pro.then((res)=>{
console.log(res , Date.now() - startDate)
})
pro.then((res)=>{
console.log(res , Date.now())
})
//1
// sucess 1005
//sucess 1560776673201
注意:状态相同,后面时间不同
第四点:注意return 与 throw的区别
Promise.resolve()
.then(() => {
return new Error(‘报错’)
})
.then((res) => {
console.log('then: ', res)
})
.catch((err) => {
console.log('catch: ', err)
})
//then: Error: return报错 直接return 返回错误信息
Promise.resolve()
.then(() => {
throw new Error(‘报错’)
})
.then((res) => {
console.log('then: ', res)
})
.catch((err) => {
console.log('catch: ', err)
})
//catch: Error: return报错 throw执行catch的报错信息
第五点:.then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环
const pro = Promise.resolve()
.then(() => {
return pro
})
pro.catch(console.error)
//TypeError: Chaining cycle detected for promise # 报错
第六点 .then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(4)
//1
注:每次调用.then 就相当于使用上一次的返回值,只有函数才能有return 返回