express.js 中的异步方法链接

async method chaining in express.js

我无法在 expressjs 中进行异步链接。第一种方法 (getUser) 工作正常并且 returns 值正确。第二种方法 (sendmail) 工作正常(邮件已发送)但它 returns 总是 undefinedmailResponse app.js 中的值总是 returns 未定义。

如果不是 运行,该方法的内部也不应该起作用,但除 return 语句外一切正常。哪里错了?

这是我的 axios 方法;

const axios = require('axios');

const getUser = async (id) => {
    try {
        const response = await axios.get('xxxxxx', {
          params: {
            id: id
          }
        });
        return response.data[0];
    } catch (err) {
        console.log(err);
    }
}

module.exports = getUser;

发送邮件方法;

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
};

const sendMail = async (data) => {
    email.send(mailOptions).then(() =>{         
        console.log("email has been sent!");
        return true;
      }).catch((err) => {
        console.log(err)
        return false;
      });
}

module.exports = sendMail;

app.js

const express = require('express');
const app = express();
const port = 3000;
const getUser = require('./fetchData');
const sendMail = require('./sendMail');
let userid = '';
let fetchedData = null;

app.get('/', (req, res) => {
    res.send('server is running');
});

app.listen(port, () => {
    console.log('App is listening');
});

app.get('/send', (req, res) => {
    userid = req.query.userid;
    
    if(!userid){
        res.status(404).send('Sorry, cant find that');
    } else {
       getUser(userid).then(axiosResponse => {
            console.log("axiosResponse => ", axiosResponse);
            fetchedData = axiosResponse;
            
            sendMail(fetchedData);
            
        }).then(mailResponse => {
            console.log("express mail response => ", mailResponse);
            res.send(mailResponse);
        });
    }
});

我从您现有的代码中看到的最大问题是您没有在 then 方法中返回任何内容。话虽这么说,我认为通过始终如一地使用 async/await 而不是将其与 Promise 语法混合使用,您会更加清晰:

// sendMail rewrite
const sendMail = async (data) => {
  try {
    await email.send(mailOptions);
    return true;
  } catch(err) {
    console.log(err);
    return false;
  }  
}

// get 'send' rewrite
app.get('/send', async (req, res) => {
  const userid = req.query.userid;
  
  if (!userid) {
    res.status(404).send('Sorry, cant find that');
    return;
  }
  
  try {
    const axiosResponse = await getUser(userid);
    console.log("axiosResponse => ", axiosResponse);
    const mailResponse = await sendMail(axiosResponse);
    console.log("express mail response => ", mailResponse);
    res.send(mailResponse);
  } catch(err) {
    // Do something with any errors here
  }
});