首页 > 解决方案 > 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);

标签: node.jsfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


在这种情况下尝试 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);
});

推荐阅读