javascript - Firebase 函数中正确链接函数

标签 javascript node.js firebase firebase-realtime-database google-cloud-functions

我正在 Firebase Cloud Functions 中构建一个函数,该函数可以利用 Node.js 模块。

我对 .then() 的使用还很陌生,并且正在努力找出一种方法来链接我的 3 个函数 webhookSend()emailSendgrid()removeSubmissionProcessor(),这些函数在 'count' 递增后立即发生(检查 temp_shouldSendWebhook 的 if 语句)。返回 promise 的整个想法仍然让我有点困惑,特别是当它涉及外部库时。

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const request = require('request');

const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

exports.submissionProcess = functions.database.ref('/submissions/processor/{submissionId}').onWrite((change, context) => {
  var temp_metaSubmissionCount = 0; // omitted part of function correctly sets the count
  var temp_shouldSendWebhook = true; // omitted part of function correctly sets the boolean

  return admin.database().ref('/submissions/saved/'+'testuser'+'/'+'meta').child('count')
    .set(temp_metaSubmissionCount + 1)
    .then(() => {

      // here is where im stuck
      if (temp_shouldSendWebhook) {
        webhookSend();
        emailSendgrid();
        removeSubmissionProcessor();
      } else {
        emailSendgrid();
        removeSubmissionProcessor();
      }

    })
    .catch(() => {
      console.error("Error updating count")
    });

});

function emailSendgrid() {
  const user = 'test@example.com'
  const name = 'Test name'

  const msg = {
      to: user,
      from: 'hello@angularfirebase.com',
      subject:  'New Follower',
      // text: `Hey ${toName}. You have a new follower!!! `,
      // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,

      // custom templates
      templateId: 'your-template-id-1234',
      substitutionWrappers: ['{{', '}}'],
      substitutions: {
        name: name
        // and other custom properties here
      }
  };
  return sgMail.send(msg)
}

function webhookSend() {
  request.post(
    {
      url: 'URLHERE',
      form: {test: "value"}
    },
    function (err, httpResponse, body) {
      console.log('REQUEST RESPONSE', err, body);
    }
  );
}

function removeSubmissionProcessor() {
  admin.database().ref('/submissions/processor').child('submissionkey').remove();
}

我希望能够构建 3 个函数来依次调用,以便它们全部执行。

最佳答案

为了链接这些函数,它们每个都需要返回一个 promise 。当它们这样做时,您可以像这样按顺序调用它们:

return webhookSend()
  .then(() => {
    return emailSendgrid();
  })
  .then(() => {
    return removeSubmissionProcessor();
  });

或者像这样并行:

return Promise.all([webhookSend, emailSendgrid, removeSubmissionProcessor]);

现在,让你的函数返回 promise :

emailSendgrid:看起来这会返回一个 promise (假设 sgMail.send(msg) 返回一个 promise ),因此您不需要更改它。

removeSubmissionProcessor:这调用一个返回 promise 的函数,但不返回该 promise 。换句话说,它会触发异步调用(admin.database....remove()),但不等待响应。如果您在该调用之前添加 return,这应该可以工作。

webhookSend 调用一个接受回调的函数,因此您需要使用 fetch (基于 Promise 的)而不是 request,或者您需要将其转换为返回 Promise 以便链接它:

function webhookSend() {
  return new Promise((resolve, reject) => {
    request.post(
      {
        url: 'URLHERE',
        form: {test: "value"}
      },
      function (err, httpResponse, body) {
        console.log('REQUEST RESPONSE', err, body);
        if (err) {
          reject(err);
        } else {
          resolve(body);
        }
      }
    );
  });
}

关于javascript - Firebase 函数中正确链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54545967/

相关文章:

java - 无法将数据从 AppCompatDialogFragment 传递到 Fragment (NullPointerException)

node.js - 将整个用户放入 session 中与仅将 Node/express 的用户 ID 放入 session 中是否安全?

node.js - 在 EC2 上使用 node.js 驱动的服务器,如何减少 TCP 连接时间?

javascript - PHP Cookie 未通过 AJAX 设置

javascript - Node.js,哈巴狗。如何设置另一个 pug 文件的链接

node.js - 通过单击提交按钮发布表单值(快速)

rest - Firebase 身份验证 + 自己的 API

android - 如何将 firebase 测试实验室与 circleci 集成

Javascript 未输入带有 .php 文件引用的函数

JavaScript:用数组解构一个对象,解构一个有对象的数组