//promsie方法
function getData(data) {
return new Promise((resolve, reject) => {
if (data === 1) {
setTimeout(() => {
resolve('getdata success')
}, 1000)
} else {
setTimeout(() => {
reject('getdata error')
}, 1000)
}
})
}
// window.onload = async () => {
// let res = await getData(1)
// console.log(res) //getdata success
// }
//1 扑获错误 try catch 方法
// try {
// let res = await getData(3)
// console.log(res)
// } catch (error) {
// console.log(res) //getdata error
// }
//2 then
// window.onload = async () => {
// let res = await getData(3).then(r=>r).catch(err=>err);
// console.log(res) //getdata error
// }
//3 better
window.onload = async () => {
let res = await getData(1)
.then((res) => [null, res])
.catch((err) => [err, null])
console.log(res) // ["getdata error",null]
}
//4 封装成工具函数
function awaitWrapper(pro){
return pro
.then((res)=>[null,res])
.catch((err)=>[err,null])
}
window.onload = async ()=>{
let res = await awaitWrapper(getData(3))
console.log(res)
}
console