一般我们会想到用 try/catch和then().catch()
function getData(data) {
return new Promise((resolve, reject) => {
if (data === 1) {
resolve('getdata success')
} else {
reject('getdata error')
}
})
}
// 这样写是捕获不到异常
async fn() {
const res = await getData();
console.log(res)
}
//方法1: try / catch
async fn() {
try {
const res = await getData();
console.log(res)
} catch {
console.log(err)
}
}
// 方法2: then().catch()
async fn() {
const res = await getData()
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
// 一般选择用如果有多个请求,则需要重复写try/catch,冗余代码,因此可以封装
test(fn) {
return new Promise(async resovle => {
try {
let res = await fn;
resolve([null, res]); // 对应【err, res】
} catch(err) {
resolve([err, null])
}
})
}
async fn() {
const [err, res] = await test(getData())
console.log(err, res)
}