我正在使用Firebase函数。基本上,一个API对应一个功能。因此,我必须在函数内返回结果。请参见下面的伪代码。
export const someAPI = functions.https.onRequest((...) =>{
parameter = get the parameter from the request
data = searchDatabase(parameter)
if data is not null
do something and create a result
else
do something else and create a different result
send the result as response.
});
我已经创建了searchDatabase
函数,并且可以正常工作。问题是,查询结果是通过回调检索的。
function searchDatabase(token:string):string
{
const db = admin.database().ref("mydata");
db.....once("value",
function(snapshot){
snapshot.forEach(
function(data)
{
const deviceId = data.val().id;
return false;
}
);
}
)
return ?; <- I need to return `deviceId` at this point.
}
我已经读过this answer,我想服用“蓝色药丸”,但是答案是针对Java的,看来TypeScript没有semaphore
。我可以在TypeScript中做类似的事情吗?
阅读评论后,我决定使用异步/等待。我不知道如何使API函数本身成为异步函数,所以我做到了。
export const someAPI = functions.https.onRequest((request, response) =>{
realFunction(request, response);
});
async function realFunction(request: express.Request, response: express.Response)
{
parameter = get the parameter from the request
data = await searchDatabase(parameter)
if data is not null
do something and create a result
else
do something else and create a different result
send the result as response.
}
并且我使searchDatabase
函数返回了Promise。
async function searchDatabase(token:string): Promise<string>
{
return new Promise<string>((resolve, reject) => {
const db = admin.database().ref("mydata");
db.orderByChild("..").equalTo(token).once("value")
.then(function(snapshot){
snapshot.forEach(
function(data)
{
//match found, but what about all other cases?
const deviceId = data.val().id;
resolve(deviceId);
return false;
}
);
resolve(null);
})
.catch(reason=>{resolve(null);})
});
}