解决catch问题
function p1 () {
return new Promise(resolve => {
setTimeout(() => {
console.log('p1 ok')
resolve('data p1')
}, 500);
})
}
function p2 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('p2 ok')
reject('data p2 fail')
}, 500);
})
}
Promise.try = async function(fn) {
try {
await fn()
}catch(e) {
return Promise.reject(e)
}
}
async function test() {
Promise.try(async () => {
let res = await p2() // 失败的请求
console.log(res)
}).catch ((error) => {
console.log(error)
})
}
test()