Javascript 仅在来自axios的请求循环完成后执行代码块
我有一个脚本,可以读取excel文件并从特定列获取数据,以便在使用axios的Google Maps API上执行搜索。对于每个请求,我都需要将其保存在Javascript 仅在来自axios的请求循环完成后执行代码块,javascript,node.js,promise,axios,Javascript,Node.js,Promise,Axios,我有一个脚本,可以读取excel文件并从特定列获取数据,以便在使用axios的Google Maps API上执行搜索。对于每个请求,我都需要将其保存在newFileList变量中。完成所有请求后,我必须将此变量的内容保存在一个文件中。但是,每当我运行代码时,保存的文件中都没有newFileList变量的内容。如何等待所有请求完成后才能将内容保存到文件中 注意:读取、写入和请求数据正在工作。我只需要在所有循环请求完成后才进行救援。我试图通过将循环放在一张期票中来解决问题,在循环执行结束时,我使用
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!");
});
你需要帮忙吗
constxlsx=require(“节点xlsx”);
常数fs=要求(“fs”);
常量坐标=要求(“/坐标”);
const resourcePath=`${uu dirname}/resources`;
const contentFile=xlsx.parse(`${resourcePath}/file-2.xlsx`)[0]。数据;
const newFile=[…contentFile,…[“纬度”,“经度”]];
(异步()=>{
试一试{
for(设i=1;i{
const{lat,lng}=response.data.results[0].geometry.location;
newFile.push([…数据,…[lat.toString(),lng.toString()]);
})
.catch((错误)=>{
控制台日志(err);
});
}
console.log(newFile);
//只有在上一个循环完全结束时,才能执行下面的代码
var buffer=xlsx.build([{name:“mySheetName”,data:newFile}]);//返回一个缓冲区
fs.writeFile(`${resourcePath}/file-3.xlsx`,缓冲区,函数(err){
如果(错误){
返回console.log(err);
}
log(“文件已保存!”);
});
}捕获(e){
控制台日志(e)
}
})();
请注意,我在coordinate.loadCoordinates
之前添加了,以确保在我们继续下一个axios请求之前完成第一个axios请求。是否需要帮助
constxlsx=require(“节点xlsx”);
常数fs=要求(“fs”);
常量坐标=要求(“/坐标”);
const resourcePath=`${uu dirname}/resources`;
const contentFile=xlsx.parse(`${resourcePath}/file-2.xlsx`)[0]。数据;
const newFile=[…contentFile,…[“纬度”,“经度”]];
(异步()=>{
试一试{
for(设i=1;i{
const{lat,lng}=response.data.results[0].geometry.location;
newFile.push([…数据,…[lat.toString(),lng.toString()]);
})
.catch((错误)=>{
控制台日志(err);
});
}
console.log(newFile);
//只有在上一个循环完全结束时,才能执行下面的代码
var buffer=xlsx.build([{name:“mySheetName”,data:newFile}]);//返回一个缓冲区
fs.writeFile(`${resourcePath}/file-3.xlsx`,缓冲区,函数(err){
如果(错误){
返回console.log(err);
}
log(“文件已保存!”);
});
}捕获(e){
控制台日志(e)
}
})();
请注意,我在
coordinate.loadCoordinates
之前添加了,以确保第一个axios请求在我们继续下一个请求之前完成。您需要使用Promise.all()
等待所有承诺得到解决。然后执行writeToFile部分。有关Promise.all()
的更多信息,请参阅
const requestPromiseArray=[];
for(设i=1;i{
//处理包含解析值的“结果”。
//实现将它们写入文件的逻辑
var buffer=xlsx.build([{name:“mySheetName”,data:results}]);
fs.writeFile(`${resourcePath}/file-3.xlsx`,缓冲区,函数(err){
如果(错误){
返回console.log(err);
}
log(“文件已保存!”);
});
})
您需要使用Promise.all()
等待所有承诺得到解决。然后执行writeToFile部分。有关Promise.all()
的更多信息,请参阅
const requestPromiseArray=[];
for(设i=1;i{
//处理包含解析值的“结果”。
//实现将它们写入文件的逻辑
var buffer=xlsx.build([{name:“mySheetName”,data:results}]);
fs.writeFile(`${resourcePath}/file-3.xlsx`,缓冲区,函数(err){
如果(错误){
返回console.log(err);
}
log(“文件已保存!”);
});
})
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,
},
})
},
};
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)
}
})();
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!");
});
})