【问题标题】:Execute block of code only after loop with requests from axios is finished仅在来自 axios 的请求的循环完成后才执行代码块
【发布时间】:2020-11-18 14:15:42
【问题描述】:

我有一个脚本,它读取一个 excel 文件并从特定列中获取数据,以便在我使用 axios 的 Google Maps API 上执行搜索。对于每个请求,我需要将其保存在 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,
        },
      })
  },
};

【问题讨论】:

    标签: javascript node.js promise axios


    【解决方案1】:

    使用async 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 请求。

    【讨论】:

      【解决方案2】:

      你需要使用Promise.all() 来等待所有的promise 都被解决。之后执行 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!");
      });
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        相关资源
        最近更新 更多