簡體   English   中英

如何僅在 Promise.all() 循環完成以及使用 javascript 的 setTimeOut() 之后執行 writeFileSync()?

[英]How to execute the writeFileSync() only after the Promise.all() loop completion along with setTimeOut() using javascript?

我正在讀取.txt文件數據並調用第3 方 api以使用 .txt 文件數據作為 arguments 連續獲取更多數據。 為此,我正在運行await Promise.all()map()循環,使用 setTimeOut setTimeOut() function 延遲 2 秒,以便第 3 方 API 獲得延遲時間並避免捕獲錯誤。

之后,我將其附加/推送到 json object 陣列。 之后將整個JSON.stringify(data)寫入.json文件。 我希望一切都按順序進行。 但不幸的是,在調試時,我看到的是writeFileSync甚至在我不想要的循環完成之前就被執行了。

這是我正在嘗試的代碼:

const writeFile = async (obj) => {
  const json = JSON.stringify(obj);
  fs.writeFileSync('/home/deb/Downloads/Twitty-Bird/src/utils/output.json', json, 'utf8')
  return 'completed';
}

export const convertToJSONFile = async () => {
  try {
    let obj = {
      table: []
    };
    const data = fs.readFileSync('/home/deb/Downloads/Twitty-Bird/src/utils/sample.txt', 'utf8');
    if (!data) throw err;
    let splitted = data.toString().split("\n");
    let interval = 2000;
    await Promise.all(splitted.map(async (word, index) => {
      setTimeout(async function () {
        let wordMeaningDetails = await axios({
        method: 'GET',
        url: `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`
        })
        wordMeaningDetails = wordMeaningDetails.data[0].meanings[0].definitions[0]
        obj.table.push({
          word: word, definition: wordMeaningDetails.definition, example: wordMeaningDetails.example
        });
      }, interval);
    }))

    const res = await writeFile(obj);
    console.log(res);
  }
  catch (err) {
    console.log("Error = ", err);
    //convertToJSONFile();
  }
}

convertToJSONFile();

我想用通俗的話完全按順序排列:

  1. 首先使用 fs.readFileSync 讀取所有數據並拆分為數組
  2. 將第 3 方 api 與 axios 和 append 所有數據一一執行到 ZA8CFDE6331BD59EB2ACZ66
  3. 然后最后將 json 數據寫入 .json 文件並保存在根文件夾中。

更新:我現在正在使用這個更新的代碼:

const promiseResponse = await Promise.all(splitted.map(async (word, index) => new Promise((resolve) => {
  setTimeout(async function () {
    let wordMeaningDetails = await findMeaning(word);
    wordMeaningDetails = wordMeaningDetails.data[0].meanings[0].definitions[0]
    obj.table.push({
      word: word, definition: wordMeaningDetails.definition, example: wordMeaningDetails.example
    });
    console.log(word);
    resolve(); // resolve the promise to mark it as "done"
  }, 1000 * index)
})
))

const res = await writeFile(obj);
console.log(res);

因此,在執行整個拆分數組並解決 promise 之后,它會引發以下錯誤,而不是執行res = await writeFile(obj). 我不知道為什么會這樣。

aa
aardvark
aargh
aback
abacus
abandon
abandoned
abandoning
abandonment
abandons
(node:78808) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404
    at createError (/home/vikas/Downloads/Twitty Bird/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/home/vikas/Downloads/Twitty Bird/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/home/vikas/Downloads/Twitty Bird/node_modules/axios/lib/adapters/http.js:293:11)
    at IncomingMessage.emit (events.js:412:35)
    at endReadableNT (internal/streams/readable.js:1334:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)
(node:78808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:78808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

您需要在 map function 中返回 Promise。 見下文:

await Promise.all(splitted.map(async (word, index) => ...)));
// You need to return a promise not a anonymous function because the function
// will resolve instantely and is not waiting for your timeout

 (async () => { await Promise.all([1, 2, 3].map((word, index) => new Promise((resolve) => { setTimeout(async function() { console.log(word); // do your api stuff resolve(); // resolve the promise to mark it as "done" }, 1000 * index) }))) console.log("done;") })();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM