【问题标题】:Each then() should return a value or throw promise/always-return每个 then() 都应该返回一个值或抛出 promise/always-return
【发布时间】:2018-09-11 06:39:25
【问题描述】:

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

警告避免嵌套承诺承诺/不嵌套

警告避免嵌套承诺承诺/不嵌套

error 每个 then() 都应该返回或抛出 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.");
            });
        });
      });
  });

【问题讨论】:

  • 这里函数的格式和缩进让人难以阅读。

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


【解决方案1】:

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

console.log("Notification Sent.");

如果你这样做了

return console.log("Notification Sent.");

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2018-09-25
    • 2020-04-02
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多