第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在等待 try 塊中的承諾解決之前調(diào)用 finally 塊

在等待 try 塊中的承諾解決之前調(diào)用 finally 塊

犯罪嫌疑人X 2022-07-08 18:00:26
我的代碼看起來(lái)像這樣:(async () => {  try {    const results = await heavyCalculation();    saveResultsToFiles(results);  } catch (e) {    handleError(e);  } finally {    process.exit(0);  }})();const saveResultsToFiles = (results) => {  results.forEach(result => {    (async () => await saveResultFile(result));  })}const saveResultFile = (result) => {  return promiseToPreprocess(result)    .then(processedResult => saveToFile(processedResult))}const promiseToPreprocess = async (result) => {  // this function returns a promise to preprocess the data}const saveToFile = (data) => {  // this function synchronously saves data to a file}我以為這段代碼會(huì)執(zhí)行計(jì)算等待每條結(jié)果被預(yù)處理并保存到文件中然后退出第一步有效,因?yàn)槌绦蛩坪踉诘却敝氐挠?jì)算結(jié)果。但是,似乎 finally 子句是在 forEach 循環(huán)中的承諾解決之前輸入的,導(dǎo)致程序提前退出。我究竟做錯(cuò)了什么?
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊

你在這里有兩個(gè)問(wèn)題:

  1. 您的forEach循環(huán)saveResultsToFiles不會(huì)返回任何內(nèi)容,因此您無(wú)法讓代碼的其他部分“等待”每個(gè)項(xiàng)目的承諾解決。

  2. saveResultFile返回一個(gè)承諾,但這個(gè)承諾不在await你的try塊中。

這兩個(gè)問(wèn)題的結(jié)果是該塊僅“開(kāi)始”保存到文件的過(guò)程,但在屈服于該塊try之前不等待它完成。finally

以下是您可以嘗試的解決方案。

  1. 您需要能夠進(jìn)行await每個(gè)saveResultFile調(diào)用,為此您需要訪問(wèn)在saveResultsToFiles. 實(shí)際上,.map您將獲得一系列結(jié)果(而不是.forEach):

const saveResultsToFiles = (results) => {

  return results.map(result => saveResultFile(result));

}

現(xiàn)在它saveResultsToFiles實(shí)際上返回了一組承諾,你應(yīng)該await在繼續(xù)之前將它們?nèi)糠祷亍_@正是Promise.all為了:

try {

    const results = await heavyCalculation();

    await Promise.all(saveResultsToFiles(results));

}


查看完整回答
反對(duì) 回復(fù) 2022-07-08
?
慕虎7371278

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊

你沒(méi)有在等待saveResultsToFiles(results);


嘗試:


(async () => {

  try {

    const results = await heavyCalculation();

    saveResultsToFiles(results);

  } catch (e) {

    handleError(e);

  } finally {

    process.exit(0);

  }

})();


const saveResultsToFiles = async (results) => {

  results.forEach(result => {

    await saveResultFile(result);

  })

}


const saveResultFile = (result) => {

  return promiseToPreprocess(result)

    .then(processedResult => saveToFile(processedResult))

}


const promiseToPreprocess = async (result) => {

  // this function returns a promise to preprocess the data

}


const saveToFile = (data) => {

  // this function synchronously saves data to a file

}


查看完整回答
反對(duì) 回復(fù) 2022-07-08
  • 2 回答
  • 0 關(guān)注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)