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

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

如何使用承諾在此 setTimeout 中正確使用拒絕?

如何使用承諾在此 setTimeout 中正確使用拒絕?

鳳凰求蠱 2022-11-27 15:52:45
AsyncTimeout 只是將 setTimeout 包裝在一個 promise 中,以便它可以在 promise 鏈中使用。但是我沒有看到實施的好地方reject()function asyncTimeout(time, callback) {  return new Promise((resolve, reject) => {    setTimeout(() => {      const results = callback();      resolve(results);    }, time );  });}asyncTimeout(1000, (test) => {  console.log('resloved');}).then(()=>{  console.log('now what')});
查看完整描述

1 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

您可以將callback()調用包裝在try/catch塊中,并reject(err)在出現異常時調用:


function asyncTimeout(time, callback) {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      try {

        const results = callback();

        resolve(results);

      } catch(err) {

        reject(err);

      }

    }, time );

  });

}

然而,正確的解決方案是根本不將回調傳遞給asyncTimeout- 只需使用返回的承諾及其then方法!承諾將永遠實現,您不需要使用reject:


function asyncTimeout(time, callback) {

  return new Promise(resolve => {

    setTimeout(resolve, time);

  });

}


asyncTimeout(1000).then(() => {

  console.log('resolved');

  throw new Error('oops');

  console.log('now what');

}).catch(err => {

  console.error('handled', err);

});


查看完整回答
反對 回復 2022-11-27
  • 1 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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