promise的状态和变化
状态
- pending: 进行中
- resolved: 成功
- rejected: 失败
状态变化
- pending-resolved =》then回调方法1
- pending-reject =》then回调方法2(优先级更高) 或 catch方法
then-error和catch哪个先执行?
结论:
- 测试发现只会执行一个,优先执行onerror
- Promise.prototype.catch是Promise.prototype.then(null, rejection)的别名
// 定义 promise
function test(){
return new Promise((_,reject)=>{
// 已知错误和异常错误 2种情形结果一样
return reject('程序错误') // "程序错误"
// return a.push(1) // ReferenceError: a is not defined
})
}
// 测试
test().then(data=>{
// 只有then-error
console.log('data=',data)
},error=>{
console.error('then error=',error)
})
// 结果: then error= 程序错误
test().then(data=>{
// 只有catch
console.log('data=',data)
}).catch(error=>{
console.error('catch error=',error)
})
// 结果: catch error= 程序错误
test().then(data=>{
// 既有then-error又有catch
console.log('data=',data)
},error=>{
console.error('then error=',error)
}).catch(error=>{
console.error('catch error=',error)
})
// 结果: then error= 程序错误
then-error和catch适用场景?
个人想法:
- 如果有多个promise链式调用,采用catch更为方便,
- 如果只有1个promise调用都可以
// 链式调用
Promise.resolve(1).then((data)=>{
console.log('data: ',data);
return 2;
}).then((data)=>{
console.log('data: ',data);
return 3;
}).then((data)=>{
console.log('data: ',data);
return 4;
}).then((data)=>{
console.log('data: ',data);
// a.push('hi'); // 程序性异常 a未定义
return Promise.reject('程序错误'); // 自定义异常
}).then((data)

这篇博客详细探讨了Promise在JavaScript中的核心概念,包括其状态变化、then-error和catch的执行顺序及适用场景、链式调用的工作原理以及在事件循环中的角色。此外,还介绍了Promise的实例方法和静态方法,如Promise.resolve、Promise.all、Promise.race及其差异,以及Promise.all和Promise.allSettled的使用情况。
最低0.47元/天 解锁文章
300

被折叠的 条评论
为什么被折叠?



