代码之家  ›  专栏  ›  技术社区  ›  T Mack

正确链接Firebase函数中的函数

  •  0
  • T Mack  · 技术社区  · 6 年前

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

    我还是个新手 .then() 我正在努力找到一种方法来链接我的3个功能 webhookSend() , emailSendgrid() removeSubmissionProcessor() 'count' 是递增的(检查 temp_shouldSendWebhook ).回馈承诺的整个想法仍然让我有点困惑,特别是当它涉及到外部图书馆时。

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

    2 回复  |  直到 6 年前
        1
  •  4
  •   helloitsjoe    6 年前

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

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

    或者像这样并行:

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

    现在,让您的函数返回承诺:

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

    removeSubmissionProcessor :这个 电话 admin.database....remove() )但不要等待回应。如果你加上 return 在打电话之前,这应该是可行的。

    webhookSend 调用接受回调的函数,因此您需要 fetch request

    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
  •  -1
  •   Vinil Prabhu    6 年前

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

    参考阅读 this