问题
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;
});
}
});
});
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/50077659/expected-catch-or-return-promise-catch-or-return