如何在Cloud Function中将数组从一个函数传递给另一个函数作为参考

时间:2017-08-06 19:00:54

标签: javascript node.js firebase google-cloud-functions geofire

我有一个函数getUsers,其中我有一个数组jsonResponse。我将该数组传递给computeData函数。我希望computeData函数应该能够在jsonResponse数组本身中添加项目。

但是代码下面没有添加相同的数组,因为它总是在response.send函数中返回空数组。

index.js

exports.getUsers = functions.https.onRequest((request, response) => {
  var x = [];

  var xLocation,
    yLocation = [],
    jsonResponse = [];

  // print algorithm name
  console.log(request.query.algo);

  let geoFire = new GeoFire(db.ref("/users/" + request.query.userId));

  geoFire.get("location").then(function(location) {
    xLocation = location;
  });

  db
    .ref("/users/" + request.query.userId)
    .once("value")
    .then(function(snapshot) {
      var jsonObject = snapshot.val();
      var basicProfileJsonObject = jsonObject.basicProfile;
      for (var key in basicProfileJsonObject) {
        if (utils.isNumber(basicProfileJsonObject[key])) {
          x.push(basicProfileJsonObject[key]);
        }
      }
      db.ref("/users/").once("value").then(function(snapshot) {
        var y = [];
        snapshot.forEach(function(item) {
          var user = item.val();
          let userId = user.basicProfile.userId;
          if (userId !== request.query.userId) {
            if (xLocation == null) {
              computeData(x, user, request.query.algo, jsonResponse);
            } else {
              let geoFire = new GeoFire(db.ref("/users/" + userId));
              geoFire.get("location").then(function(location) {
                if (location === null) {
                  console.log(
                    "Provided key is not in GeoFire, will ignore profile"
                  );
                  computeData(x, user, request.query.algo, jsonResponse);
                } else {
                  console.log("Provided key has a location of " + location);
                  var distance = GeoFire.distance(xLocation, location); // in km
                  console.log("Distance: " + distance);

                  if (distance < 15) {
                    computeData(x, user, request.query.algo, jsonResponse);
                  }
                }
              });
            }
          }
        });
        response.send(jsonResponse);
      });
    });
});

function computeData(x, user, algo, jsonResponse) {
  var similarityCount,
    y = [];

  var basicProfileJsonObject = user.basicProfile;
  for (var key in basicProfileJsonObject) {
    if (utils.isNumber(basicProfileJsonObject[key])) {
      y.push(basicProfileJsonObject[key]);
    }
  }

  if (algo === "cosine") {
    // compute cosine value
    similarityCount = cosineUtils.cosineSimilarity(x, y);
  } else if (algo == "euclidean") {
    // compute euclidean distance value
    similarityCount = 1 / (1 + euclidean(x, y));
  } else if (algo === "pearson-correlation") {
    // compute pearson correlation coefficents
    similarityCount = pcorr.pearsonCorrelation(x, y);
  }
  console.log(x);
  console.log(y);
  console.log(similarityCount);
  jsonResponse.push(user);
}

是否有人知道如何将数组作为参考传递并在Cloud Function for Firebase中将项目添加到其中?

1 个答案:

答案 0 :(得分:1)

您的promise语句是response.send(jsonResponse);,这意味着您的循环将在您的else语句中到达computeData()时完成并调用Promise.all

尝试类似这样的内容,它不会触及所有变量,但主要思想是将resolved与计算值一起使用exports.getUsers = functions.https.onRequest((request, response) => { // blah blah var y = []; // store promises that resolves your computed value snapshot.forEach(function(item) { // blah blah if (xLocation == null) { y.push(Promise.resolve(computeData()); } else { y.push(computeAnotherData(userId)); } }); Promise.all(y) .then(values => { response.send(values); }); }); function computeAnotherData(userId) { let geoFire = new GeoFire(db.ref("/users/" + userId)); return geoFire.get("location").then(function(location) { return computeData(); }); } -

// i have try using this import, but still not work
/*import flash.events.Event;
  import flash.media.Sound;
  import flash.net.URLRequest;
*/

// here is the code
var req:URLRequest=new URLRequest("music.mp3");
var snd:Sound=new Sound();
snd.load(req);
var chan:SoundChannel=snd.play();// not work using 'snd.play(1);' too

chan.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete); 
function onPlaybackComplete(event:Event){
  trace("Musik Complete");
}

希望它有意义。