每个 then() 都应该返回一个值或抛出 Firebase 云函数 [英] Each then() should return a value or throw Firebase cloud functions

查看:25
本文介绍了每个 then() 都应该返回一个值或抛出 Firebase 云函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javascript 为 firebase 编写云函数,但我被卡住了,我不知道错误的确切含义并且无法解决它..错误状态:27:65 错误每个 then() 应该返回一个值或抛出 promise/always-return

I am writing a cloud function for firebase using javascript but I am stuck, I don't know the exact meaning of error and unable to solve it.. The error states: 27:65 error Each then() should return a value or throw promise/always-return

'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 回调只需要返回一个值.

The then callback just needs to return a value.

然而,eslint 可能会抱怨代码中嵌套的 then(),这也是一种反模式.您的代码的结构应该更像这样:

However, eslint may then complain about nested then() in your code, which is also an anti-pattern. Your code should really be structured more like this:

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');
});

请注意,每个然后相互链接,而不是相互嵌套.

Note that each then chains off of each other, rather than being nested inside each other.

这篇关于每个 then() 都应该返回一个值或抛出 Firebase 云函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆