2 回答

TA贡献1815条经验 获得超6个赞
这是我的最终代码,使用 try catch 块捕获错误。
它有效,但我认为它损害了可读性。
async function templateAction(action) {
try {
console.log('Template Action BEFORE calling action');
await action();
console.log('Template Action AFTER calling action');
}
catch(err) {
console.log('I was caught and logged');
console.log(err);
}
}
function action() {
return new Promise(async (resolve,reject) => {
try {
console.log('I am sync from action function BEFORE async call');
await mockAPI();
console.log('I am sync from action function AFTER async call');
resolve();
}
catch(err) {
console.log('I was caught');
reject(err);
}
});
}
function mockAPI() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log('I am from async mockAPI call');
resolve();
},1500);
});
}
templateAction(action);
添加回答
举报