任何超出简单承诺的事情通常都会让我感到困惑。在这种情况下,我需要对 N 个对象连续执行 2 次异步调用。首先,我需要从磁盘加载一个文件,然后将该文件上传到邮件服务器。我更喜欢一起做这两个动作,但我已经通过首先完成所有读取和所有上传来让它工作。下面的代码有效,但我不禁认为它可以做得更好。我不明白的一件事是为什么 when.all 不拒绝。我对文档的解释似乎暗示如果其中一个承诺拒绝,.all 将拒绝。为了测试错误,我已经注释掉了较低的解析。没有错误,事情似乎工作正常并且有意义。
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;
}