[英]How can I convert the following JavaScript Promise into regular asychronous code?
Hi I'm working with the following code snippet: 嗨,我正在使用以下代码片段:
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() } ]
});
I'm trying to remove Promises and turn the code into code using callbacks. 我正在尝试删除Promises,然后使用回调将代码转换为代码。
At the moment, I'm looping through all the attachments and when I print an individual attachment to the console I get: 目前,我正在浏览所有附件,当我在控制台上打印单个附件时,我得到:
Promise { <pending> }
How can I convert the code to regular callback code such that I can access the 'filename' and 'data' attributes of the attachment? 如何将代码转换为常规回调代码,以便可以访问附件的“文件名”和“数据”属性?
Actually, I don't understand why you need to go back from a promise to a callback but you can use the following code. 实际上,我不明白为什么您需要从承诺返回到回调,但是您可以使用以下代码。 It just a promise converter:
它只是一个承诺转换器:
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);
});
};
};
To use it 使用它
promiseToCallback(promise)(function(err, data) {
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.