【问题标题】:How can I execute one function after another in NodeJs?如何在 NodeJs 中一个接一个地执行一个函数?
【发布时间】: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


    【解决方案1】:

    第二个函数只会在第一行中等待的 Promise 被解析或拒绝时执行。所以它肯定应该在第一个函数完成之后执行第二个函数

    【讨论】:

    • 问题是当我从index.js 运行这个main() 函数时,结果是找不到这个名为clients.json 的JSON 文件。那是因为第一个函数没有完成。
    【解决方案2】:

    为了等待工作,你必须从下划线函数返回承诺。 在你的 json 文件准备好后包装你的 main 函数 promise 并解析

    return new Promise((resolve, reject) => {

    // some processing
    resolve();
    
    // reject if something goes wrong
    

    });

    【讨论】:

    • 你能帮我举个例子吗?在我的情况下如何使用?
    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 2014-02-07
    • 2013-12-22
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多