变量不从函数中获取返回值

问题描述 投票:1回答:1

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

我正在使用mailgun api发送邮件,而ordermessage只是选择'undefined'。但是send-mail一直在运行。

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

没有。

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

发送-在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 <[email protected]>',
    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。

node.js sails.js mailgun
1个回答
0
投票

这是一个猜测:我认为mailgun.messages().send(...)方法不会返回任何内容,因为它使用了经典的回调。所以你总会得到它的undefined

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

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`
}
© www.soinside.com 2019 - 2024. All rights reserved.