如何运行多个firebase承诺,然后一旦完成,执行功能
Posted
技术标签:
【中文标题】如何运行多个firebase承诺,然后一旦完成,执行功能【英文标题】:how to run multiple firebase promises and then once completed, execute function 【发布时间】:2018-05-26 07:11:12 【问题描述】:我需要执行2 firebase calls
以从数据库中检索特定数据。 Once these promises resolve
,我想用检索到的数据调用另一个函数。我怎样才能做到这一点? ..Promise.All?
的东西
代码如下:
app.post('/testtwilio', function(req, res)
//save request variables
var to_UID = req.body.to;
var from_UID = req.body.from;
var experience_id = req.body.exp_id;
//Query firebase and save 'zone_id' which we need later
firebase.database().ref('experiences').child(experience_id).once('value').then((snap) =>
zone_id = snap.val().ZoneID;
);
//Query firebase and save 'from_name' which we need later
firebase.database().ref('users').child(from_UID).once('value').then((snap) =>
from_name = snap.val().Name;
);
//Once we have the two variables returned and saved
//Call a final firebase query and a twilio function with all the recieved data
firebase.database().ref('users').child(to_UID).once('value').then((snap) =>
//Do something with this aggregated data now
client.messages.create(
//blah blah do something with the saved data that we retrieved
var phone = snap.val().Phone;
var msg = from_name + zone_id + from_UID + experience_id
);
);
);
【问题讨论】:
【参考方案1】:是的,您可以使用Promise.all
,因为once('value')
返回一个。
快速和肮脏的例子:
var promises = [];
promises.push(firebase.database().ref('experiences').child(experience_id).once('value'));
promises.push(firebase.database().ref('users').child(from_UID).once('value'));
// Wait for all promises to resolve
Promise.all(promises).then(function(res)
// res[0] is your experience_id snapshot
// res[1] is your from_UID snapshot
// Do something...
);
【讨论】:
【参考方案2】:如果您使用的是 NodeJS 7.6 及更高版本,您还可以使用 async 函数编写此代码,这样更易于阅读和维护
// ...
const wrap = require('express-async-wrap')
// ...
// need to wrap async function
// to make it compatible with express
app.post('/testtwilio', wrap(async (req, res) =>
const to_UID = req.body.to
const from_UID = req.body.from
const experience_id = req.body.exp_id
const [
snap1,
snap2,
snap3
// waiting for all 3 promises
] = await Promise.all([
firebase.database().ref('experiences').child(experience_id).once('value'),
firebase.database().ref('users').child(from_UID).once('value'),
firebase.database().ref('users').child(to_UID).once('value')
])
const zone_id = snap1.val().ZoneID
const from_name = snap2.val().Name
const phone = snap3.val().Phone
const msg = from_name + zone_id + from_UID + experience_id
// ...
client.messages.create(...)
))
【讨论】:
以上是关于如何运行多个firebase承诺,然后一旦完成,执行功能的主要内容,如果未能解决你的问题,请参考以下文章
Firebase 函数 tslint 错误 必须正确处理承诺