1.Promise对象 用来执行 业务函数
- 如果 业务成功,则 应该调用 resolve 函数,实参 会被 传给 then 回调函数中
- 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 回调函数中
- 如果 出现异常,则 可以手动 会 自动 抛出异常,异常对象 会被 传给 catch 回调函数中
function hmtest() {
new Promise(function (resolve, reject) {
JSON.parse('asdfasdfasdf')
}).then((res1) => {
console.log('res1->', res1)
}).catch((e) => {
console.log('---------------------------')
console.log('出错啦:')
console.dir(e)
console.log('---------------------------')
})
}
2.Promise对象 结合 async/await 关键字
- 如果 业务成功,则 应该调用 resolve 函数,实参 会被返回给 前面的 res
- 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 回调函数中
- 如果 出现异常,则 可以手动或自动抛出异常,异常对象会被传给catch 回调函数中
async function hmtest1() {
const res = await new Promise(function (resolve, reject) {
throw new Error('死鬼!');
}).catch((e) => {
console.log('---------------------------')
console.log('出错啦:')
console.dir(e)
console.log('---------------------------')
})
console.log('res->', res)
}
}
hmtest2()
3.Promise对象 结合 async/await + try...catch... 代码块
- 如果 业务成功,则 应该调用 resolve 函数,实参 会被返回给 前面的 res
- 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 代码块的形参
- 如果 出现异常,则 可以手动或自动抛出异常,异常会被传给 catch 代码块的形参
async function hmtest2() {
try {
const res = await new Promise(function (resolve, reject) {
throw new Error('死鬼!');
})
console.log(res)
} catch (e) {
console.log('---------------------------')
console.log('出错啦:')
console.dir(e)
console.log('---------------------------')
}
}