为了账号安全,请及时绑定邮箱和手机立即绑定

仅在来自 axios 的请求循环完成后才执行代码块

仅在来自 axios 的请求循环完成后才执行代码块

梦里花落0921 2022-12-09 13:45:16
我有一个脚本可以读取 excel 文件并从特定列获取数据以在我使用 axios 的 Google Maps API 上执行搜索。对于发出的每个请求,我都需要将其保存在newFileList变量中。完成所有请求后,我必须将这个变量的内容保存在一个文件中。newFileList但是,每当我运行我的代码时,文件都会在没有变量内容的情况下被保存。在能够将内容保存在文件中之前,如何等待所有请求完成?注意:读取、写入和请求数据正在工作。我只需要在所有循环请求完成后才进行救援。我试图通过将循环放在一个 promise 中来解决这个问题,并在我使用的这个循环执行结束时使用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 completelyvar buffer = xlsx.build([{ name: "mySheetName", data: newFile }]); // Returns a bufferfs.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,        },      })  },};
查看完整描述

2 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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)

    }

})();

请注意,我在之前添加了awaitcoordinate.loadCoordinates,以确保在我们继续下一个请求之前完成第一个 axios 请求。



查看完整回答
反对 回复 2022-12-09
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

您需要使用Promise.all()等待,直到所有承诺都得到解决。之后执行 writeToFile 部分。

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!");

});

})


查看完整回答
反对 回复 2022-12-09
  • 2 回答
  • 0 关注
  • 197 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信