我正在使用Node.js设置一个API服务器,利用IMAP Node模块解析来自我的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);
});
控制台在 API 调用时返回
undefined
。如何使此调用同步?