【问题标题】:Should I use response.send() in 'finally' block when writing Google Cloud Functions?在编写 Google Cloud Functions 时,我应该在“finally”块中使用 response.send() 吗?
【发布时间】:2020-07-20 00:04:37
【问题描述】:

我试图更好地理解将 Promise 与 Google Cloud Functions 一起使用。我刚刚了解了 Promise 上的“finally”方法,它在链中的所有 Promise 都被完全解决或拒绝后调用。在 http 函数中,将 response.send() 放在 finally 方法中是一种好习惯吗?

以下代码对 http 请求使用 request-promise-native。在第一个 .then() 中,我调用了 parseSchedule,它使用cheerio 网络抓取 api 循环访问一些数据和网站,并将其添加到 scheduleGames 数组中(我认为是同步的)。

我从那里返回,然后将该数据记录到 writeDB 中的控制台,但我注意到的一件事是,在我在日志中看到来自 scheduleGames 的数据之前,我看到 response.send() 日志“执行完成”。对吗?

我应该像这样使用“finally”块吗? 谢谢,

    const options = {
        uri: 'https://www.cbssports.com/nba/schedule/' + urlDate,
        Connection: 'keep-alive',
        transform: function (body) {
            return cheerio.load(body);
        }
    };

    return request(options)
    .then(parseSchedule)
    .then(writeSchedule)
    .catch((err) => console.log("there was an error: " + err))
    .finally(res.send("execution finished"));

    function parseSchedule($){

          const scheduledGames = [];

            $('tbody').children('tr').each((i, element) => {

                const gameTime = $(element).children('td').eq(2).find('a').text()
                const scheduledGame = { gameTime: gameTime};

                scheduledGames.push(scheduledGame);

        });

        return scheduledGames;
   }

    function writeDB(scheduledGames){
        console.log(scheduledGames);     
    }

}

【问题讨论】:

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


    【解决方案1】:

    当一切都成功时,在 Promise 链中发送成功响应,或者在 catch 处理程序中发送错误响应,通常更有意义。如果你做了这两件事,那么使用 finally 毫无意义,因为成功和错误是你真正需要处理的仅有的两种情况。除非您有特殊情况,否则请坚持成功和错误。

    【讨论】:

    • 补充道格刚才所说的, finally 块可用于记录,关闭任何流,最后进行一些清理。但除此之外,在您的用例中,成功和错误场景就足够了!
    • 谢谢你们,我现在明白为什么不需要像那样使用 .finally 了,以及应该如何使用 .finally ,但仍然不明白为什么理论上它不会(并且在我的案子没有)工作。 .finally() 不是最后调用的吗?
    • 如果没有看到你的函数的整个代码,就无法确定(你在这里只展示了一点)。
    • finally 的一个问题是缺少在 try 中创建的变量不可用。因此,您必须在尝试之外进行尝试,如果您想捕获该代码上的任何错误,它将无法正常工作。我今天终于使用了关闭数据库连接 f.ex。就像 LearningEveryday 提到的那样,关闭流。希望你找到了一个好的解决方案@LouisSankey
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2020-12-19
    • 2013-08-14
    • 1970-01-01
    相关资源
    最近更新 更多