Google Functions:异步方法不要等到最后

时间:2019-07-23 07:07:19

标签: node.js asynchronous promise google-cloud-functions

我正在使用Google Functions,我需要创建一个将CSV复制到数据库中的函数。

我编写了函数,并且在本地运行良好。 但是当它在GoogleFunctions上时,我有一个ECONNRESET。 我用谷歌搜索,发现它是因为我使用了promise,而我需要等待的promise必须由我的函数返回。 然后我像这样返回这个承诺:

const METHOD = 'POST';

exports.admin_indicateur_import_data_csv = async (req, res) => {
    try {
        if (req.method === "OPTIONS") {
            res.status(200);
            res.set({
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": METHOD,
                "Access-Control-Allow-Headers": ["POST", "PUT"].includes(METHOD) ? "Authorization, Content-Type, content-encoding, Accept-Encoding" : "Authorization, content-encoding, Accept-Encoding"
            });
            return res.end();
        }
        if (req.method !== METHOD) {
            return res.status(405).send("METHOD not allowed");
        }

        // Check token
        const r = await axios({
            method: "GET",
            url: "...",
            headers: {
                Authorization: req.headers["authorization"]
            }
        });

        if (r.status !== 200) {
            return res.status(401).send("Unauthorized");
        }
        if (!await __is_role(req, ['Admin', 'Super Admin'])) {
            return res.status(403).send('Forbidden');
        }

        const datas = req.body.data;
        let csv = '';

        const promise = new Promise((resolve, reject) => {
            // Connect to db
            pool.connect((err, client, done) => {
                let fsStream = client.query(copyFrom('COPY table FROM STDIN WITH (FORMAT CSV, DELIMITER \';\')'));

                fsStream.on('end', () => {
                    pool.end();
                    res.set({
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Credentials": "true",
                    });
                    res.status(200).send('OK');
                    resolve('OK');
                });
                fsStream.on('error', (e) => {
                    pool.end();
                    return res.status(500).send(e.message);
                    reject(e);
                });

                for (const data of datas) {
                    csv += `some data\n`;

                    if (csv.length > 30878915) {
                        fsStream.write(csv);
                        csv = '';
                    }
                }
                fsStream.write(csv);
                fsStream.end(null);
            });
        });

        return await promise; // I already try with 'return promise;'
    } catch (e) {
        return res.status(500).send(e.message);
    }
};

0 个答案:

没有答案