Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled rejection from Cloud Function, but it runs sometimes

I have some code that works sometimes, but sometimes it does not. When it does not run, I get this error:

enter image description here

This is my code in Javascript:

exports.handleRequest = functions.database.ref('/Request/{usersUID}/{autoID}/{request}').onWrite(event => {
  let request = event.data.val();
  let additionalRequest = event.data.key;
  let usersUID = event.params.usersUID;
  const generatedAutoID = event.params.autoID;
  event.data.adminRef.remove();
  if (event.data.previous.exists()) {
        return;
  }
  if (!event.data.exists()) {
        return;
  }
  const functions = require('firebase-functions');
  const admin = require('firebase-admin');
  admin.initializeApp(functions.config().firebase);
  var db = admin.database();

  var MasterAllCards = ["2_of_clubs", "2_of_spades", "2_of_diamonds", "2_of_hearts", "3_of_clubs", "3_of_spades", "3_of_diamonds", "3_of_hearts", "4_of_clubs", "4_of_spades", "4_of_diamonds", "4_of_hearts", "5_of_clubs", "5_of_spades", "5_of_diamonds", "5_of_hearts", "6_of_clubs", "6_of_spades", "6_of_diamonds", "6_of_hearts", "7_of_clubs", "7_of_spades", "7_of_diamonds", "7_of_hearts", "8_of_clubs", "8_of_spades", "8_of_diamonds", "8_of_hearts", "9_of_clubs", "9_of_spades", "9_of_diamonds", "9_of_hearts", "10_of_clubs", "10_of_spades", "10_of_diamonds", "10_of_hearts", "jack_of_clubs", "jack_of_spades", "jack_of_diamonds", "jack_of_hearts", "queen_of_clubs", "queen_of_spades", "queen_of_diamonds", "queen_of_hearts", "king_of_clubs", "king_of_spades", "king_of_diamonds", "king_of_hearts", "ace_of_clubs", "ace_of_spades", "ace_of_diamonds", "ace_of_hearts"]
  var MasterAllValues = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14]
  function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  let pathToUsersTickets = db.ref('/users/' + usersUID + '/serverSideValues/Tickets');
  var usersTickets = 0;
  pathToUsersTickets.transaction(function(current) {
        return (current || 0) - 1;
  }).then(function(ticket) {
        usersTickets = Number(ticket.snapshot.val())
  });
  if (usersTickets >= 0) {
        let pathSettingUpGame = db.ref('/Checkrequests/' + usersUID + '/' + request); 
        let pathServer = db.ref('/Checkrequests/' + usersUID + '/' + request + '/Server');
        var tags = [];
        var images = [];
        var allCards = MasterAllCards
        var allCardsTags = MasterAllValues
        var i = 0;
        while (i < 5) {
              let randomc = getRandomInt(0, 51 - i);
              images.push(allCards[randomc])
              tags.push(allCardsTags[randomc])
              allCards.splice(randomc, 1);
              allCardsTags.splice(randomc, 1);
              i++
        }
        console.log(images);
        console.log(tags[0])
        console.log(allCards);
        console.log(allCardsTags) 
        pathSettingUpGame.update({
              "mastercard": images[0],
              "highlowgametier" : 1
        })    
        pathServer.update({
              "child1image" : images[1],
              "child2image" : images[2],
              "child3image" : images[3],
              "child4image" : images[4],
              "child1tag" : tags[1],
              "child2tag" : tags[2],
              "child3tag" : tags[3],
              "child4tag" : tags[4],
        })
   }
})

But sometimes it DOES run without any errors. You can check the code on here, where images[0] always is a string and never empty. How can this problem sometimes occur? No error: enter image description here

And sometimes I get this, notice the undefined in the third value: enter image description here

like image 619
J. Doe Avatar asked Apr 28 '17 23:04

J. Doe


People also ask

Why does cloud deployment fail?

Cloud Functions deployment can fail if the entry point to your code, that is, the exported function name, is not specified correctly. Your source code must contain an entry point function that has been correctly specified in your deployment, either via Cloud console or Cloud SDK.

How do I stop the cloud function execution?

You cannot disable a function. Just comment the function body. It would be a good practice to log the call in the console and then return null so you can keep track whenever the function is invoked.


1 Answers

The intermittent failures may be the result of your not returning a Promise for the numerous asychronous Firebase operations your code performs. The Cloud Functions Guide explains:

It's important to manage the lifecycle of a function to ensure that it resolves properly... Also, you can make sure that the Cloud Functions instance running your function does not shut down before your function successfully reaches its terminating condition or state.

  • Resolve functions that perform asynchronous processing by returning a JavaScript promise

Your code contains calls to remove(), transaction() and update(). Each of these completes asynchronously and returns a Promise. You need to chain or combine (see Promise.all()) the returned Promises, as needed, to ensure your function returns a Promise for any ongoing, asynchronous Firebase operation.

For example, to handle the two calls to update() at the end of the posted code:

const prom1 = pathSettingUpGame.update({
    ...
});

const prom2 = pathServer.update({
    ...
});

return Promise.all([prom1, prom2]);

There is also a Firebase video on returning Promises.

like image 164
Bob Snyder Avatar answered Sep 30 '22 16:09

Bob Snyder