我收到一个Object有一个产品ID列表及其数据库的ref,所以我必须在我的数据库中搜索每个产品才能得到它的价格,我试过这样的事情
const functions = require('firebase-functions');
const cors = require('cors')({
origin: true
});
const admin = require('firebase-admin');
var request = require('request');
admin.initializeApp();
exports.GeraPagSeguro = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method === 'POST') {
var xml;
req.body.map((product) => {
admin.database().ref(product.refitem).once('value', (snapshot) => {
const value = snapshot.val();
const price = value.price;
xml += price;
//rest of code building the xml i want
})
})
//rest of code sending the xml via POST to other server
})
})
})
问题是,wait
的所有承诺的其余代码都没有map
。
要等待多个异步操作完成,请使用Promise.all()
:
var xml;
var promises = [];
req.body.map((product) => {
promises.push(admin.database().ref(product.refitem).once('value', (snapshot) => {
const value = snapshot.val();
const price = value.price;
return price;
})
})
Promise.all(promises).then((prices) => {
prices.forEach((price) => {
...
});
//rest of code sending the xml via POST to other server
});
由于firebase数据库函数返回Promise
,您可以将函数转换为异步函数并在其上调用await
。像这样:
exports.GeraPagSeguro = functions.https.onRequest(async (req, res) => {
cors(req, res, () => {
if (req.method === 'POST') {
var xml;
req.body.map((product) => {
const snapshot = await admin.database().ref(product.refitem).once('value')
const value = snapshot.val();
const price = value.price;
xml += price;
//rest of code building the xml i want
})
//rest of code sending the xml via POST to other server
})
})
})
然后你可以执行其他代码,就像他们“等待”firebase操作一样
注意:在默认的Firebase功能设置中未启用异步功能,您需要在emcaVersion
文件中将.eslintrc.json
指定为2017或8(默认值为7),以确保Async相关功能正常工作。它应该如下所示:
{
"parserOptions": {
"ecmaVersion": 2017 //or 8
}
}
除此之外,你还需要添加promise
作为插件,如下所示:
"plugins": [
"promise"
]
如果.eslintrc.json
中有任何指定es6
用法的内容,请将其更改为es7
。