假如有3个函数,返回的都是一个promise,f2依赖f1返回的结果后才能执行,f3依赖f2返回的结果才能执行,这会导致回调地狱的写法,还是一层嵌套一层
async function f1() {
return 1
}
async function f2() {
return 2
}
async function f3() {
return 3
}
f1().then(res => {
console.log(res);
f2().then(res => {
console.log(res);
f3().then(res => {
console.log(res);
})
})
})
用以下这种写法就可以避免,在上一个回调里返回一个下一个要执行的函数,返回的也是promise
f1()
.then(res => {
console.log(res);
return f2()
})
.then(res => {
console.log(res);
return f3()
}).then(res => {
console.log(res);
})
如果其中一个出错了 咋办?因为是链式调用,可以在最后面用catch捕获
async function f1() {
return 1
}
async function f2() {
return Promise.reject(2)
}
async function f3() {
return 3
}
f1()
.then(res => {
console.log(res);
return f2()
})
.then(res => {
console.log(res);
return f3()
}).then(res => {
console.log(res);
}).catch(e => {
console.log('错误是', e);
})
当然也可以用async await
async function f1() {
return 1
}
async function f2() {
return Promise.reject(2)
}
async function f3() {
return 3
}
async function test() {
try {
let res1 = await f1()
console.log(res1);
let res2 = await f2()
console.log(res2);
let res3 = await f3()
console.log(res3);
} catch (error) {
console.log('错误是', error);
}
}
test()