亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果序列中的承諾之一拋出錯誤,則按順序解決承諾并打破序列

如果序列中的承諾之一拋出錯誤,則按順序解決承諾并打破序列

翻過高山走不出你 2023-03-10 15:51:23
假設我async設置了三個函數,如下所示:const stepOne = async () => { setTimeout(function() {  console.log("step 1")}, 3000)  }const stepTwo = async () => { throw new Error("Error at step two") }const stepThree = async () => { console.log("step 3") }我將如何按順序執行所有這些函數并在 stepTwo 處打破承諾鏈,不允許 stepThree 函數運行?所以,正常順序是這樣的:stepOne --> stepTwo --> stepThree在 stepTwo 處拋出錯誤的序列:stepOne --> stepTwo在 stepTwo 拋出的錯誤需要在 end catch 塊中被捕獲。更新#1:錯過了問題的關鍵要素。await 不能使用,因為這三個函數需要在非異步函數中調用。例子:const testFunc = () => {     resolve three promises   sequentially, break the promise chain when error is thrown   and ultimately, catch errors here     }
查看完整描述

3 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

如果您解決承諾,您的代碼將起作用stepOne,因為setTimeout只是將函數添加到堆棧而不是等待它解決。


如果您要返回一個 PromisestepOne并在之后解決它,console.log那么它將try catch等待stepOne并捕獲錯誤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);

        })  

})();

現在console.log看起來像這樣


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)


查看完整回答
反對 回復 2023-03-10
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

請嘗試以下代碼。您需要等待每次調用(stepOne、stepTwo 和 stepThree),以便在出現異常時不會進行下一次調用。


try {

    await stepOne();

    await stepTwo();

    await stepThree()

} catch (error) {

    console.log(error);

}


查看完整回答
反對 回復 2023-03-10
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

如果您的步驟是返回 Promise 的函數,您可以創建一個包裝函數,它將按順序調用每個步驟并在步驟失敗時中止,并記錄失敗步驟的詳細信息。


在此示例中,每個步驟失敗的概率為五分之一。


// 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);


查看完整回答
反對 回復 2023-03-10
  • 3 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號