javascript - 每个 then() 应该返回一个值或抛出 Promise/Always-return

标签 javascript node.js firebase google-cloud-functions eslint

我正在创建一个推送通知应用程序,我使用node.js来部署firebase功能,但是在部署时显示错误。

warning Avoid nesting promises promise/no-nesting

warning Avoid nesting promises promise/no-nesting

error Each then() should return or throw promise/always-return

这是我的代码:

"use-strict";

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore
  .document("Users/{user_id}/Notification/{notification_id}")
  .onWrite(event => {
    const user_id = event.params.user_id;
    const notification_id = event.params.notification_id;

    return admin
      .firestore()
      .collection("Users")
      .doc(user_id)
      .collection("Notification")
      .doc(notification_id)
      .get()
      .then(queryResult => {
        const from_user_id = queryResult.data().from;
        const from_message = queryResult.data().message;
        const from_data = admin
          .firestore()
          .collection("Users")
          .doc(from_user_id)
          .get();
        const to_data = admin
          .firestore()
          .collection("Users")
          .doc(user_id)
          .get();

        return Promise.all([from_data, to_data]).then(result => {
          const from_name = result[0].data().name;
          const to_name = result[1].data().name;
          const token_id = result[1].data().token_id;
          const payload = {
            notification: {
              title: "Notification From :" + from_name,
              body: from_message,
              icon: "default"
            }
          };

          return admin
            .messaging()
            .sendToDevice(token_id, payload)
            .then(result => {
              console.log("Notification Sent.");
            });
        });
      });
  });

最佳答案

你没有提到错误在哪里。我认为错误将在行

console.log("通知已发送。");

如果你这样做

return console.log("通知已发送。");

错误应该消失,而警告仍然存在。

正如 Marcos 上面提到的,最好将 Promise 链接起来而不是嵌套。

关于javascript - 每个 then() 应该返回一个值或抛出 Promise/Always-return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49604619/

相关文章:

javascript - 如何复制 Node/Electron 中的图像文件并将其作为文件粘贴到 Windows 中的另一个目录?

java - Firebase 数据库监听器返回空值

javascript - 如何将多个 promise 链接到 Firebase 中的单个事务中

Firebase 云消息传递与 Postman : Connection error as soon as I add authorization

mysql - 如何在nodejs中进行动态的mysql查询次数?

javascript - 防止从周围激活菜单

javascript - 存储来自 AngularJS 输入表单的数据

php - 更改 Facebook API 事件订阅仅在单击某个“喜欢”按钮时才运行?

javascript - Ajax 页面内容;先前单击的链接在点击后退按钮后第二次的行为不一样

node.js - 使用jade创建无序列表树