【问题标题】:Properly chaining functions in Firebase function在 Firebase 函数中正确链接函数
【发布时间】:2019-02-06 02:49:39
【问题描述】:

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

我对@9​​87654322@ 的使用仍然很陌生,我正在努力寻找一种方法来链接我的 3 个函数 webhookSend()emailSendgrid()removeSubmissionProcessor(),这发生在 'count' 之后递增(检查 temp_shouldSendWebhook 的 if 语句)。返回承诺的整个想法仍然让我有些困惑,尤其是当它涉及外部库时。

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

我希望能够构建三个函数一个接一个地调用,这样它们都会执行。

【问题讨论】:

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


【解决方案1】:

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

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

或者像这样并行:

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

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

emailSendgrid:看起来这会返回一个承诺(假设sgMail.send(msg) 返回一个承诺),所以你不需要更改它。

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

【讨论】:

  • 这是我正在寻找的确切解释。谢谢你这么详细。我将能够在未来的项目中利用这个示例,我希望其他人也可以!
【解决方案2】:

使用异步函数,然后您可以在每个函数调用之前使用 .then() 或 await

参考阅读this

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2019-09-21
    相关资源
    最近更新 更多