在Firebase云功能中等待地图内的快照值

问题描述 投票:0回答:2

我收到一个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

node.js firebase firebase-realtime-database google-cloud-functions
2个回答
1
投票

要等待多个异步操作完成,请使用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
});

1
投票

由于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

© www.soinside.com 2019 - 2024. All rights reserved.