簡體   English   中英

僅在來自 axios 的請求的循環完成后執行代碼塊

[英]Execute block of code only after loop with requests from axios is finished

我有一個腳本,它讀取 excel 文件並從特定列獲取數據以在 Google 地圖 API 上執行搜索,其中我使用 axios。 對於每個請求,我需要將其保存在newFileList變量中。 完成所有請求后,我必須將此變量的內容保存在文件中。 但是,每當我運行我的代碼時,文件都會被保存而沒有newFileList變量的內容。 在能夠將內容保存在文件中之前,如何等待所有請求完成?

注意:讀取,寫入和請求數據正在工作。 我只需要在所有循環請求完成后才能進行救援。 我試圖通過將循環放在一個承諾中來解決,並且在這個循環的執行結束時我使用了resolve

const xlsx = require("node-xlsx");
const fs = require("fs");
const coordinate = require("./coordinate");

const resourcePath = `${__dirname}/resources`;
const contentFile = xlsx.parse(`${resourcePath}/file-2.xlsx`)[0].data;
const newFile = [[...contentFile, ...["Latitude", "Longitude"]]];

for (let i = 1; i < contentFile.length; i++) {
  const data = contentFile[i];
  const address = data[2];
  coordinate
    .loadCoordinates(address)
    .then((response) => {
      const { lat, lng } = response.data.results[0].geometry.location;
      newFile.push([...data, ...[lat.toString(), lng.toString()]]);
    })
    .catch((err) => {
      console.log(err);
    });
}

console.log(newFile);

//The code below should only be executed when the previous loop ends completely

var buffer = xlsx.build([{ name: "mySheetName", data: newFile }]); // Returns a buffer
fs.writeFile(`${resourcePath}/file-3.xlsx`, buffer, function (err) {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

坐標文件:

const axios = require("axios");

module.exports = {
  loadCoordinates(address) {
    const key = "abc";
    return axios
      .get(`https://maps.googleapis.com/maps/api/geocode/json`, {
        params: {
          address,
          key,
        },
      })
  },
};

使用異步IIFE 會有幫助嗎?

const xlsx = require("node-xlsx");
const fs = require("fs");
const coordinate = require("./coordinate");

const resourcePath = `${__dirname}/resources`;
const contentFile = xlsx.parse(`${resourcePath}/file-2.xlsx`)[0].data;
const newFile = [[...contentFile, ...["Latitude", "Longitude"]]];

(async() => {
    try{
        for (let i = 1; i < contentFile.length; i++) {
          const data = contentFile[i];
          const address = data[2];
          await coordinate
            .loadCoordinates(address)
            .then((response) => {
              const { lat, lng } = response.data.results[0].geometry.location;
              newFile.push([...data, ...[lat.toString(), lng.toString()]]);
            })
            .catch((err) => {
              console.log(err);
            });
        }

        console.log(newFile);

        //The code below should only be executed when the previous loop ends completely

        var buffer = xlsx.build([{ name: "mySheetName", data: newFile }]); // Returns a buffer
        fs.writeFile(`${resourcePath}/file-3.xlsx`, buffer, function (err) {
          if (err) {
            return console.log(err);
          }
          console.log("The file was saved!");
        });
    } catch(e) {
        console.log(e)
    }
})();

請注意,我在coordinate.loadCoordinates之前添加了await ,以確保在我們繼續下一個請求之前完成第一個 axios 請求。

您需要使用Promise.all()等到所有承諾都得到解決。 之后執行 writeToFile 部分。 有關Promise.all()的更多信息,您可以參考https://www.javascripttutorial.net/es6/javascript-promise-all/

const requestPromiseArray = [];

for (let i = 1; i < contentFile.length; i++) {
  const data = contentFile[i];
  const address = data[2];
  requestPromiseArray.push(coordinate
    .loadCoordinates(address))
}

Promise.all(requestPromiseaArray).then(results=>{
     // Handle "results" which contains the resolved values.
      // Implement logic to write them onto a file
    var buffer = xlsx.build([{ name: "mySheetName", data: results }]);
    fs.writeFile(`${resourcePath}/file-3.xlsx`, buffer, function (err) {
      if (err) {
         return console.log(err);
       }
     console.log("The file was saved!");
});
})

暫無
暫無

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

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