最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unhandled rejection from Cloud Function, but it runs sometimes - Stack Overflow

programmeradmin4浏览0评论

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

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:

And sometimes I get this, notice the undefined in the third value:

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

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:

And sometimes I get this, notice the undefined in the third value:

Share Improve this question edited Apr 20, 2018 at 20:14 Marie 3041 silver badge7 bronze badges asked Apr 28, 2017 at 23:57 J. DoeJ. Doe 13.1k9 gold badges75 silver badges140 bronze badges 2
  • You're not showing the entire function. I don't know what kind of function this is (database?) or what all the variables are (db?). What are you returning from the function? Have you tried putting console.log() statement in there to validate that the values are what you think they are? – Doug Stevenson Commented Apr 29, 2017 at 1:51
  • I want to generate 5 random cards (strings for the image reference and tags) and upload them to the database. I updated my question with some more pictures. I can not understand why this is happening... – J. Doe Commented Apr 30, 2017 at 13:50
Add a ment  | 

1 Answer 1

Reset to default 7

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 pletes asynchronously and returns a Promise. You need to chain or bine (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.

发布评论

评论列表(0)

  1. 暂无评论