Firebase Cloud Functions Cron异步功能多个调用

时间:2019-01-29 22:27:57

标签: node.js firebase google-app-engine async-await google-cloud-functions

我有云功能。它是由App Engine Cron作业触发的。它每小时都会通过Google Cloud Pub / Sub触发我的Firebase Cloud Function。我一次获取我的Firebase实时数据库,并为每个值循环。问题是我的main.async函数多次调用。我使用一个i变量进行循环,我的控制台记录的日志数比我的数据库长度还多。我的意思是,如果我的数据库长度为4,但是for循环运行8或15或23次。该值随机变化。我想循环获取每个数据库值,在Internet上获取一些数据,完成后,寻找下一个值。这是代码:

use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var request = require('request-promise').defaults({ encoding: null });
var fs = require('fs');
// Get a reference to the Cloud Vision API component
const Vision = require('@google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
var os = require("os");
var databaseArray = [];
var uniqueFilename = require('unique-filename')

exports.hourly_job = functions.pubsub
  .topic('hourly-job')
  .onPublish((event) => {
    console.log("Hourly Job");

    var db = admin.database();
    var ref = db.ref("myData")

   ref.once("value").then(function(allData) {

   allData.forEach(function(deviceToken) {

          deviceToken.forEach(function(firebaseIDs) {

        var deviceTokenVar = deviceToken.key;
        var firebaseIDVar = firebaseIDs.key;
        var firstvalue = firebaseIDs.child("firstvalue").val();
        var secondvalue = firebaseIDs.child("secondvalue").val();


        var items = [deviceTokenVar, firebaseIDVar, firstvalue, secondvalue];

        databaseArray.push(items);

});   

});
return databaseArray;
}).then(function (databasem) {

    main().catch(console.error);                
        });

return true;
});

const main = async () => {

    var i;
    for (i = 0; i < databaseArray.length; i++) {

        console.log("Database Arrays " + i + ". elements: ");

         if (databaseArrayfirst != "") {

        var apiUrl = "http://api.blabla;

        try {
        const apiBody = await request.get(apiUrl); 


    ///////////////////////////vison start//////////////////////    

        const visionResponseBody = await vision.documentTextDetection(apiBody)

         var visionResponse = visionResponseBody[0].textAnnotations[0].description;

         ...some logic here about response...

/////////////////////////////////////////////////   
         var getdatabasevar = await admin.database().ref("myData/" + databaseArrayDeviceToken + "/" + databaseArrayFirebaseID);

         await getdatabasevar.update({
         "firstvalue": visionResponse
         });  


/////////////////////////////////////////////////  

} catch (error) {
        console.error(error);
        }
///////////////////////////vison end//////////////////////  
    }

};
return true;
};

谢谢。

0 个答案:

没有答案