Anything beyond a simple promise usually has me perplexed. In this case I need to do 2 asynch calls in a row on N number of objects. First, I need to load a file from disk, then upload that file to a mail server. I prefer to do the two actions together, but I have gotten it working by doing all the reads first and all the uploads second. The code below works, but I can't help but think it can be done better. One thing I don't understand is why the when.all doesn't reject. My interpretation of the docs seems to imply that if one of the promises rejects, the .all will reject. I've commented out the lower resolves in order to test errors. With no errors things seem to work fine and make sense.
mail_sendOne({
from: 'greg@',
to: 'wilma@',
subject: 'F&B data',
attachments: [
{name: 'fred.html', path: '/fred.html'},
{name: 'barney.html', path: '/barney.html'}
]
})
.done(
function(res) {
console.log(res)
},
function(err) {
console.log('error ', err);
}
)
function mail_sendOne(kwargs) {
var d = when.defer();
var promises = [], uploadIDs = [], errs = [];
// loop through each attachment
for (var f=0,att; f < kwargs.attachments.length; f++) {
att = kwargs.attachments[f];
// read the attachment from disk
promises.push(readFile(att.path)
.then(
function(content) {
// upload attachment to mail server
return uploadAttachment({file: att.name, content: content})
.then(
function(id) {
// get back file ID from mail server
uploadIDs.push(id)
},
function(err) {
errs.push(err)
}
)
},
function(err) {
errs.push(err)
}
))
}
// why doesn't this reject?
when.all(promises)
.then(
function(res) {
if (errs.length == 0) {
kwargs.attachments = uploadIDs.join(';');
sendEmail(kwargs)
.done(
function(res) {
d.resolve(res);
},
function(err) {
d.reject(err);
}
)
}
else {
d.reject(errs.join(','))
}
}
)
return d.promise;
}
function readFile(path) {
var d = when.defer();
var files = {
'/fred.html': 'Fred Content',
'/barney.html': 'Barney Content'
}
setTimeout(function() {
d.reject('Read error');
//d.resolve(files[path]);
}, 10);
return d.promise;
}
function uploadAttachment(obj) {
var d = when.defer();
setTimeout(function() {
d.reject('Upload error');
//d.resolve(new Date().valueOf());
}, 10);
return d.promise;
}
function sendEmail(kwargs) {
var d = when.defer();
setTimeout(function(){
console.log('sending ', kwargs)
}, 5);
return d.promise;
}