2 回答

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 請求。

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!");
});
})
添加回答
舉報