【发布时间】: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