3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果您解決承諾,您的代碼將起作用stepOne,因?yàn)閟etTimeout只是將函數(shù)添加到堆棧而不是等待它解決。
如果您要返回一個(gè) PromisestepOne并在之后解決它,console.log那么它將try catch等待stepOne并捕獲錯(cuò)誤stepTwo
這是您的代碼示例
const stepOne = async () => {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("step 1")
resolve(true);
}, 3000)
});
}
const stepTwo = async () => { throw new Error("Error at step two") }
const stepThree = async () => {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("step 3")
resolve(true);
}, 3000)
});
}
(() => {
stepOne()
.then(stepTwo)
.then(stepThree)
.catch(error => {
console.log(error);
})
})();
現(xiàn)在console.log看起來(lái)像這樣
step 1
Error: Error at step two
at stepTwo (/home/user/develop/test/stackoverflow.js:10:38)
at processTicksAndRejections (internal/process/task_queues.js:93:5)

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
請(qǐng)嘗試以下代碼。您需要等待每次調(diào)用(stepOne、stepTwo 和 stepThree),以便在出現(xiàn)異常時(shí)不會(huì)進(jìn)行下一次調(diào)用。
try {
await stepOne();
await stepTwo();
await stepThree()
} catch (error) {
console.log(error);
}

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果您的步驟是返回 Promise 的函數(shù),您可以創(chuàng)建一個(gè)包裝函數(shù),它將按順序調(diào)用每個(gè)步驟并在步驟失敗時(shí)中止,并記錄失敗步驟的詳細(xì)信息。
在此示例中,每個(gè)步驟失敗的概率為五分之一。
// Make a step proc, that throws 1 time in 5
function createStep(index) {
let error = (Math.random() < 0.2) ? new Error(`Step ${index+1} error`) : null ;
return () => new Promise((resolve, reject) => setTimeout(error ? reject(error): resolve(`Step ${index+1} outcome`), 500));
}
async function runSteps(steps) {
for(stepIndex = 0; stepIndex < steps.length; stepIndex++) {
try {
console.log(`Running step #${stepIndex+1}...`);
let result = await steps[stepIndex]();
console.log(`Step result:`, result);
} catch (e) {
console.error(`An error occurred at step #${stepIndex+1}:`, e.message);
break;
}
if (stepIndex === (steps.length -1) ) {
console.log("All steps completed successfully");
}
}
}
let steps = Array.from( { length: 3 }, (v,k) => createStep(k));
runSteps(steps);
添加回答
舉報(bào)