亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在來自 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條經驗 獲得超3個贊

您需要使用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 關注
  • 277 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號