变量没有从函数中获取返回值

Variable not picking up returned value from function

我正在尝试将两个函数(send-mail 和 sendsms)的 returned 值收集到一个变量 (var ordermessage) 中。它从 send-sms 中获取 returned 值就好了。

我正在使用 mailgun api 发送邮件,而 ordermessage 刚收到 'undefined'。但是发送邮件保持 运行.

我试过`await mailgun.messages().send(...)`
我试过`const myvar = await mailgun.messages().send(...)`
还有`let myvar = await mailgun.messages().send...`

纳达。

我尝试使用一个将 api 调用作为回调的函数。仍然不确定。电子邮件和短信都已发送,但我需要电子邮件服务器的回复。我正在使用 Mailgun 试用版,所以我需要 return 回复。

发送-mail.js

var mailgun = require('mailgun-js')({apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN});
  var processresponse = "\n";

  var data = {
    from: 'Zigy Demo Store <admin_demo@zigy.com>',
    to: email,
    subject: 'You have placed an order.',
    text: body
  };

  console.log("\n----------START EMAIL-------------\n");

mailgun.messages()
  .send(data, function (error, body) {
    console.log("\nFinally running MAILGUN. Return body is\n", body);
    if (body == undefined || body == false) { 
      console.log("Got nothing from server.");
    } else {
      processresponse += body.message;
      console.log("***********************Gotten reply from Mailgun server.*******************************\n", processresponse);
    }
  });

OrderController 函数

module.exports = {
    neworder: async function(req, res) {
        var sendemail = require('./send-mail');
        var sendtext = require('./send-sms');

        var orderdetails = 'New order created at '+ new Date() + '\nItem  ---> Price'; //Message that will be sent to users.
        var item;
        var printcart = await Shoppingcart.findOne({
            where: {
                id: req.body.cart,
                owner: req.body.user
            }
        }).populate('product');
        var ordermessage = '';

        for (items in printcart.product) {
            item = printcart.product[items];
            orderdetails += '\n' + item.name + ' ---> ' + item.price;
        }
        console.log(orderdetails);
        //to get email addr and phone number
        phone = req.body.phone; 
        var email = req.body.email;

        var user = await User.findOne({id:printcart.owner});

        ordermessage += await sendemail(email, orderdetails); 
        console.log("\nAfter email, the message is ", ordermessage);

        ordermessage += await sendtext(phone, orderdetails);
        console.log("\nAfter text, Printing order message to be returned to browser ", ordermessage);

        console.log("Final message ", ordermessage);

        res.send(ordermessage);
    }
};

航站楼

----------START EMAIL-------------

Calling test function

After email, the message is  


Finally running MAILGUN. Return body is
 { id:
   '<20190222062410.1.FD7A4868FA0ADF5E@sandbox612cf746219c46ad93d5dc588f9341ff.mailgun.org>',
  message: 'Queued. Thank you.' }
***********************Gotten reply from Mailgun server.*******************************

Queued. Thank you.
Checking list of verified numbers...
Found the phonenumber!
You will receive an SMS message with your order details soon.

After text, Printing order message to be returned to browser  
You will receive an SMS message with your order details soon.
Final message  
You will receive an SMS message with your order details soon.
SM9bc04208f9354834a153fb1ffd7dc8bb

任何帮助将不胜感激。

编辑:我从 send-mail.js 和 send-sms.js 内部调用了 res.write 并去掉了变量 ordermessage。

这是一个猜测:我认为 mailgun.messages().send(...) 方法没有 return 任何东西,因为它使用了经典回调。所以你总是会从中得到undefined

但是你从回调中的 body 参数中得到了结果。您可以使用 Promisify 将回调转换为承诺样式方法。

const util = require('util');
const fs = require('fs');

const messages = mailgun.messages();

const sendPromisified = util.promisify(messages.send());
sendPromisified(data).then((body) => {
  // Do something with `body`
}).catch((error) => {
  // Handle mailgun error
});

// Async / await style
try {
   const mailBody = await sendPromisified(data);
} catch (err) {
   // handle mailgun error `err`
}