I am new to JavaScript.This is my first function in javascript to deploy a function on the firebase.
Got this error:
- [eslint] Unexpected function expression. (prefer-arrow-callback)
- [eslint] Expected catch() or return (promise/catch-or-return)
What is wrong with this function?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
.onCreate(event => {
var uid = event.params.uid;
admin.database().ref('users/${uid}/referred_by')
.once('value').then(function(data) {
var referred_by_somebody = data.val();
if (referred_by_somebody) {
var moneyRef = admin.database()
.ref('/users/${uid}/inventory/pieces_of_eight');
moneyRef.transaction(function(current_value) {
return (current_value || 0) + 50;
});
}
});
});
This function has one argument: reason. The rejection reason. The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is fulfilled.
catch : when a promise fails, you catch the error, and do something with the error information. finally : when a promise settles (fails or passes), you can finally do something.
The main difference between the forms promise. then(success, error) and promise. then(success). catch(error) is that in case if success callback returns a rejected promise, then only the second form is going to catch that rejection.
catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.
The first error suggests you to use an arrow function as a callback. So you need to replace the regular functions, (function() { ... })
, with arrow functions, (() => { ... })
.
The second error suggests that you either need to catch the promise rejection, or return the promise itself. I am not too sure about your code but I believe that this method:
admin.database().ref('users/${uid}/referred_by').once('value')
returns a promise. So it needs to be returned like this:
return admin.database().ref('users/${uid}/referred_by').once('value')
or handle the error like this:
admin.database().ref('users/${uid}/referred_by').once('value')
// ... your code here
.catch(error => { ... });
As @Bergi pointed out in the comments that returning the promise is not preferable here, you may just add a catch
block to your promise.
In order to solve promise/catch-or-return
, just add a .catch(() => null)
at the end of the line. And of course, don't forget to actually implement the error handling logic at some point in the not-so-distant future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With