我正在使用javascript为firebase编写一个云函数,但我被卡住了,我不知道错误的确切含义,也无法解决它。。错误状态:27:65 error Each then((应返回一个值或抛出promise/始终返回
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
if (!change.after.val()) {
return console.log('A Notification has been deleted from the database : ', notification_id);
}
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "New Friend Request",
body: "You Have Received A new Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
更改此项:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
对此:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
return null; // add this line
});
then
回调只需要返回一个值。
然而,esint可能会抱怨代码中嵌套的then()
,这也是一种反模式。您的代码的结构应该更像这样:
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
// redacted stuff...
return admin.messaging().sendToDevice(token_id, payload);
}).then(() => {
console.log('This was the notification Feature');
});
请注意,然后每一个都会彼此连锁,而不是嵌套在彼此内部。
更改此项:
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
进入这个:
return admin.messaging().sendToDevice(token_id, payload).then(response=>{
console.log('This was the notification Feature');
return true;
},err=>
{
throw err;
});
正如错误所说,当使用then
时,您需要返回一个值。
这是在告诉您每个.then
必须包含一个返回值。换句话说,避免承诺反模式。
您可能会发现async
函数更容易理解。请注意,您需要运行Node 8运行时以获得异步支持。。。