Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正确链接Firebase函数中的函数_Javascript_Node.js_Firebase_Firebase Realtime Database_Google Cloud Functions - Fatal编程技术网

Javascript 正确链接Firebase函数中的函数

Javascript 正确链接Firebase函数中的函数,javascript,node.js,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Realtime Database,Google Cloud Functions,我正在Firebase Cloud Functions中构建一个函数,它可以利用Node.js模块 我对.then()的使用还是新手,我正在努力找到一种方法来链接我的3个函数webhookSend()、emailSendgrid()、以及removeSubmissionProcessor(),它们发生在'count'增加之后(检查temp\u shouldSendWebhook的if语句). 归还承诺的整个想法仍然让我有点困惑,特别是当它涉及到外部图书馆时 const functions = r

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

我对
.then()
的使用还是新手,我正在努力找到一种方法来链接我的3个函数
webhookSend()
emailSendgrid()
、以及
removeSubmissionProcessor()
,它们发生在
'count'
增加之后(检查
temp\u 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();
}
const functions=require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp();
const request=require('request');
const firebaseConfig=JSON.parse(process.env.FIREBASE\u CONFIG);
const SENDGRID_API_KEY=firebaseConfig.SENDGRID.KEY;
const sgMail=require('@sendgrid/mail');
setApiKey(SENDGRID_API_KEY);
exports.submissionProcess=functions.database.ref('/submissions/processor/{submissionId}').onWrite((更改,上下文)=>{
var temp_metaSubmissionCount=0;//函数的省略部分正确设置了计数
var temp_shouldSendWebhook=true;//函数的省略部分正确设置布尔值
返回admin.database().ref('/submissions/saved/'+'testuser'+'/'+'meta').child('count'))
.set(临时提交计数+1)
.然后(()=>{
//这就是我被卡住的地方
如果(临时应发送Webhook){
webhookSend();
emailSendgrid();
removeSubmissionProcessor();
}否则{
emailSendgrid();
removeSubmissionProcessor();
}
})
.catch(()=>{
控制台错误(“错误更新计数”)
});
});
函数emailSendgrid(){
常量用户test@example.com'
常量名称='测试名称'
常数msg={
致:用户:,
发件人:'hello@angularfirebase.com',
主题:"新追随者",,
//text:`Hey${toName}。你有了一个新的追随者!!!`,
//html:`嘿${toName}。你有了一个新的追随者!!!`,
//自定义模板
templateId:'your-template-id-1234',
替换包装器:['{','}}'],
替换:{
姓名:姓名
//和其他自定义属性
}
};
返回sgMail.send(msg)
}
函数webhookSend(){
请寄(
{
url:'URLHERE',
形式:{test:“value”}
},
功能(错误、httpResponse、正文){
日志('请求-响应',错误,正文);
}
);
}
函数removeSubmissionProcessor(){
admin.database().ref('/submissions/processor').child('submissionkey').remove();
}

我希望能够构造3个要逐个调用的函数,以便它们都能执行。

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


参考阅读

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

return webhookSend()
  .then(() => {
    return emailSendgrid();
  })
  .then(() => {
    return removeSubmissionProcessor();
  });
return Promise.all([webhookSend, emailSendgrid, removeSubmissionProcessor]);
或者像这样并行:

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

如果您对承诺在云功能中的使用感到困惑,您应该观看文档中的视频系列。这正是我想要的解释。谢谢你这么详细。我将能够在未来的项目中利用这个例子,我希望其他人也能这样做!