【发布时间】:2021-10-22 17:17:12
【问题描述】:
你好吗?
我是 NodeJs 开发的新手,我想在我的示例中了解如何在来自另一个文件的文件 index.js 中运行函数。
为了更好地理解,这是我正在使用的代码。此函数将客户端列表写入 JSON 文件。 index.js 上的第二个函数需要该文件才能运行。此 JSON 必须存在,因为它将更新此 JSON 文件。
const keys = require("../service.json");
const { google } = require("googleapis");
const fs = require("fs");
async function main() {
const client = new google.auth.JWT(keys.client_email, null, keys.private_key, ["https://www.googleapis.com/auth/spreadsheets.readonly"]);
client.authorize(function (err) {
if (err) {
console.log(err);
return;
} else {
getClients(client).then(function (clients) {
const data = [];
for (let index = 0; index < clients[0].data.values.length; index++) {
if (clients[0].data.values[index][0] != undefined) {
try {
let iteration = {
name: clients[0].data.values[index][0],
id: clients[1].data.values[index][0],
value: parseInt(clients[2].data.values[index][0]),
value2: "",
date: "",
};
data.push(iteration);
} catch (error) {
console.log(error);
}
}
}
fs.writeFileSync("./clients.json", JSON.stringify(data, null, 2), finished);
function finished(err) {
if (err) {
console.log(err);
}
}
});
}
});
async function getClients(client) {
const gsapi = google.sheets({ version: "v4", auth: client });
const clientsData = [];
const options = {
spreadsheetId: "xxx",
range: "yyy",
};
clientsData.push(await gsapi.spreadsheets.values.get(options));
options["range"] = "xxx";
clientsData.push(await gsapi.spreadsheets.values.get(options));
options["range"] = "yyy";
clientsData.push(await gsapi.spreadsheets.values.get(options));
return clientsData;
}
}
module.exports = { main };
这是index 文件:
这个想法是运行第一个函数getclients.main(),它将生成 JSON 文件。完成此功能后,将启动第二个,即puppeteerExport.main()。之后将使用第三个函数exportBQ.uploadToBq() 将文件上传到 BigQuery。
const exportBQ = require("./modules/exportToBQ");
const getClients = require("./modules/getClients");
const puppeteerExport = require("./modules/puppeteer");
async function main() {
await getClients.main();
puppeteerExport.main();
exportBQ.uploadToBq();
};
main();
如何保证第二个函数只有在第一个函数完成后才会执行?你能帮帮我吗?
【问题讨论】:
标签: node.js function asynchronous async-await google-bigquery