我正在 nodejs 中设置一个 API 服务器,用于使用 IMAP 节点模块解析来自我的 Gmail 帐户的电子邮件。但是当我从我的 Angular 应用程序调用请求 /api/fetch-email 时,它会在电子邮件解析完成之前返回控件。
我的 api 服务器文件
app.get('/api/fetch-email', async (req, res, next)=>{
let emails = await email.email();
console.log(console.log);
});
email.js 模块
var Imap = require('imap'),
inspect = require('util').inspect;
let email_array = [];
var imap = new Imap({
user: 'myemail',
password: 'password',
host: 'imap.gmail.com',
port: 993,
tls: true
});
let email = async()=>{
imap.connect();
return imap.once('end', async function() {
console.log('Connection ended');
return new Promise((resolve, reject)=>{
resolve(email_array);
flag = true
});
});
}
exports.email = email;
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
}
imap.once('ready', function() {
email_array = [];
flag = false;
openInbox(function(err, box) {
if (err) throw err;
imap.search([ ['SUBJECT', 'TEST'], ['ON', 'Oct 7, 2019']],
async function(err, results) {
if (err) throw err;
var f = imap.fetch(results, { bodies: '' });
var root = builder.create('blocktick');
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
const chunks = [];
stream.on("data", function (chunk) {
chunks.push(chunk);
});
stream.on("end", function () {
let string = Buffer.concat(chunks).toString('utf8');
email_array.push(string);
});
});
msg.once('end', function() {
console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
});
});
});
});
imap.once('error', function(err) {
console.log(err);
});
控制台返回undefinedapi 调用。我怎样才能使这个调用同步?