可以使用 Promise 或者 async/await 来解决按顺序调用函数的问题。
使用 Promise 的做法如下所示:
function firstFunction() {
console.log('This is the first function');
return Promise.resolve('From first function');
}
function secondFunction() {
console.log('This is the second function');
return Promise.resolve('From second function');
}
function thirdFunction() {
console.log('This is the third function');
return Promise.resolve('From third function');
}
firstFunction()
.then(result => {
console.log(result);
return secondFunction();
})
.then(result => {
console.log(result);
return thirdFunction();
})
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
使用 async/await 的做法如下所示:
async function main() {
try {
const result1 = await firstFunction();
console.log(result1);
const result2 = await secondFunction();
console.log(result2);
const result3 = await thirdFunction();
console.log(result3);
} catch (error) {
console.error(error);
}
}
main();
无论是使用 Promise 还是 async/await,都可以保证函数按顺序被调用,并且能够捕获到错误。
上一篇:按顺序调用服务并使用结果中的参数
下一篇:按顺序调用类/对象方法