您好我正在使用以下代码段:
imaps.connect(config).then(function (connection) {
connection.openBox('INBOX').then(function () {
// Fetch emails from the last 24h
var delay = 24 * 3600 * 1000;
var yesterday = new Date();
yesterday.setTime(Date.now() - delay);
yesterday = yesterday.toISOString();
var searchCriteria = ['UNSEEN', ['SINCE', yesterday]];
var fetchOptions = { bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'], struct: true };
// retrieve only the headers of the messages
return connection.search(searchCriteria, fetchOptions);
}).then(function (messages) {
var attachments = [];
messages.forEach(function (message) {
var parts = imaps.getParts(message.attributes.struct);
attachments = attachments.concat(parts.filter(function (part) {
return part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT';
}).map(function (part) {
// retrieve the attachments only of the messages with attachments
return connection.getPartData(message, part)
.then(function (partData) {
return {
filename: part.disposition.params.filename,
data: partData
};
});
}));
});
return Promise.all(attachments);
}).then(function (attachments) {
console.log(attachments);
// =>
// [ { filename: 'cats.jpg', data: Buffer() },
// { filename: 'pay-stub.pdf', data: Buffer() } ]
});
我尝试删除Promise并使用回调将代码转换为代码。
目前,我循环浏览所有附件,当我打印到控制台的单个附件时,我得到:
Promise { <pending> }
如何将代码转换为常规回调代码,以便我可以访问&#39;文件名&#39;和&#39;数据&#39;附件的属性?
答案 0 :(得分:0)
实际上,我不明白为什么你需要从承诺回到回调,但你可以使用以下代码。它只是一个承诺转换器:
const promiseToCallback = function (promise) {
if (!isFn(promise.then)) {
throw new TypeError('Expected a promise');
}
return function (cb) {
promise.then(function (data) {
setImmediate(cb, null, data);
}, function (err) {
setImmediate(cb, err);
});
};
};
使用它
promiseToCallback(promise)(function(err, data) {
...
});