超越简单承诺的任何事情通常让我感到困惑.在这种情况下,我需要在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 …Run Code Online (Sandbox Code Playgroud)