Promise status and changes
state
- pending: in progress
- resolved: successful
- rejected: failed
status change
- pending-resolved =》then callback method 1
- pending-reject =》then callback method 2 (higher priority) or catch method
Which one is executed first, then-error or catch?
in conclusion:
- The test found that only one will be executed, and onerror will be executed first.
- Promise.prototype.catch is an alias for 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= 程序错误
What are the applicable scenarios for then-error and catch?
personal idea:
- If there are multiple promise chain calls, it is more convenient to use catch.
- It is ok if there is only one promise call
// 链式调用
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)