承诺不会根据要求返回价值

时间:2018-02-20 10:50:27

标签: node.js

我一直试图让这个工作,但我是NodeJS的新手。我怀疑这个问题是由于异步,但我不熟悉它是如何工作的。

此代码背后的想法是它监视firebase数据库更改并向用户发送电子邮件。我从更改快照获取所有内容,并使用值检查另一个表以获取用户数据。在发送电子邮件之前,请求未返回,我不确定原因。

编辑我应该在收到请求的结果之前指定电子邮件功能sgMail。我试过延迟,但我仍然没有得到结果及时返回。

这是我的index.js

 // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
var requestify = require('requestify');

//SendGrid
const SENDGRID_API_KEY = functions.config().sendgrid.key;

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);


// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.packingListEmail = functions.database.ref('Order/{orderID}')
   .onUpdate(event => {

  // Grab the current value of what was written to the Realtime Database.
  const eventSnapshot = event.data;

  //Here You can get value through key
  var shipperInfo = eventSnapshot.child("fk_shipper_id").val();
  var travelerInfo = eventSnapshot.child("fk_traveler_id").val();

  //Print value of string
  console.log(shipperInfo);

  //Get Shipper Info

  const shipperPath = 'https://shlep-me-f516e.firebaseio.com/User/'+shipperInfo+'.json';

  requestify.get(shipperPath)
     .then(function(response) {
          // Get the response body (JSON parsed or jQuery object for XMLs)
          shipperResult = response.getBody();
          console.log(shipperResult.email);
      return shipperResult;
      });

  function getTravelerData() {
      return new Promise(resolve => {
          requestify.get('https://shlep-me-f516e.firebaseio.com/User/' + travelerInfo + '.json')
             .then(function (response) {
              resolve(response.getBody())
          });
      });
    }

  var TravelD = getTravelerData();


  //Send an email

  const msg = {
      to: 'andrew@shlepme.com',
      from: 'support@shlepme.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: 'd1ccfeb9-2e2d-4979-a3ca-c53975fe486e',
      substitutionWrappers: ['%', '%'],
      substitutions: {
          '%shipper_name%': "Test",
          'traveler_name': TravelD.name
          // and other custom properties here
        }
      };

      console.log('Sending email');
      console.log(TravelD);
      return sgMail.send(msg)
});

有什么想法吗?我一直试图解决这个问题。

1 个答案:

答案 0 :(得分:1)

您似乎需要首先了解Promise。

当你开始使用promises时,你需要始终使用它们并将一个链接到另一个。

所以我会像这样重写你的代码:(未经测试)

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require("firebase-functions");
var requestify = require("requestify");

//SendGrid
const SENDGRID_API_KEY = functions.config().sendgrid.key;

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(SENDGRID_API_KEY);

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.packingListEmail = functions.database
    .ref("Order/{orderID}")
    .onUpdate(event => {
        // Grab the current value of what was written to the Realtime Database.
        const eventSnapshot = event.data;

        //Here You can get value through key
        var shipperInfo = eventSnapshot.child("fk_shipper_id").val();
        var travelerInfo = eventSnapshot.child("fk_traveler_id").val();

        //Print value of string
        console.log(shipperInfo);

        //Get Shipper Info
        const shipperPath = "https://shlep-me-f516e.firebaseio.com/User/" + shipperInfo + ".json";

        requestify.get(shipperPath)
            .then(function(response) {
                // Get the response body (JSON parsed or jQuery object for XMLs)
                var shipperResult = response.getBody();
                console.log(shipperResult.email);
                return shipperResult;
            })
            .then(function (shipperResult) {
                //Send an email
                const msg = {
                    to: "andrew@shlepme.com",
                    from: "support@shlepme.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: "d1ccfeb9-2e2d-4979-a3ca-c53975fe486e",
                    substitutionWrappers: ["%", "%"],
                    substitutions: {
                        "%shipper_name%": "Test",
                        traveler_name: shipperResult.name
                        // and other custom properties here
                    }
                };
                console.log("Sending email");
                console.log(shipperResult);
                return sgMail.send(msg);
            });
    });
相关问题