node.js - firebase 函数是否保证异步函数的执行顺序?
问题描述
我有一个 firebase 函数,它在 firebase 实时数据库中进行大量检查,然后返回响应。
firebase 中的节点运行时是否保证异步函数将按调用顺序执行?或者有某种非fifo调度程序然后执行?
真实函数的逻辑有点复杂(超过 200 行),所以为了避免额外的复杂性,我将使用伪函数作为示例:
function checks(req,res){
let resp;
database.ref('nodeA').once('value').then(function(data) {
//do some checks and modify resp
});
database.ref('nodeB').once('value').then(function(data) {
//do some checks and modify resp
});
database.ref('nodeC').once('value').then(function(data) {
//do some checks and modify resp
res.status(200).send(resp);
});
首先。我知道我可以对实时数据库进行嵌套调用并保证执行所有检查,但我的真实案例场景比这更复杂,对我不起作用
是否有任何保证所有检查都将由此示例代码执行?
如果不是......我如何在等待它准备好时进行非阻塞?喜欢:
while(!resp.ready){
wait //how to wait without blocking the other functions
}
res.status(200).send(resp);
解决方案
在这种情况下尝试 async 和 await ,在您的代码中,您将在完成所有验证之前将响应发送给用户,不能保证每个 Promise 的回调函数将以相同的顺序执行。
async function checks(req,res){
let resp;
let nodeAData=await database.ref('nodeA').once('value');
//do some checks and modify resp
let nodebData=database.ref('nodeB').once('value')
//do some checks and modify resp
.
.
.
res.status(200).send(resp);
});
推荐阅读
- java - 如何比较 HashMaps
> 当值对的顺序不正确时 - django - Azure webapp 部署 docker 容器未响应 HTTP ping
- python - 带有标题标签的 BS4 类
- c# - 将 Asp.Mvc 和 Web.Api 在同一个解决方案中部署到 IIS
- amazon-web-services - 如何在 EC2 终止期间删除 AWS CloudWatch 警报
- scala - How to get integer value with leading zero in Spark (Scala)
- python - 如何合并两个都包含所需关键字的文本片段?
- javascript - Gulp watch 只检测到第一个变化
- ruby-on-rails - 只渲染一次部分
- java - 关于 System.out.printf 的问题 / 关于输出的问题