0

我有一个将文件上传到服务器并返回承诺的函数。我想检查每个承诺何时完成并显示“成功部署文件名..”的日志。

我不关心承诺的顺序,但是 Q.all() 对我没有帮助,因为它仅在所有承诺完成或失败时快速失败时才返回。

我想写一些东西来检查我的一个承诺何时完成并显示日志。由于每个文件都可能很大,我希望用户能够收到迄今为止上传的内容的提醒。

当我的一个文件失败时,用户将看到如下内容:

Successfully deployed file1.txt
Successfully deployed file2.txt
Failed deploying file3.txt
4

2 回答 2

3

为什么不简单地遍历您的文件(或承诺)?

var files = ['file1.txt', 'file2.txt'/*, ...*/];
files.forEach(function (file) {
  uploadFile(file).done(function () {
    console.log('Successfully deployed ' + file);
  }, function () {
    console.log('Failed deployed ' + file);
  });
});
于 2013-10-15T12:43:08.120 回答
0

@kamituel's answer works perfectly. If you need fail-fast behavior though (as you requested in the comment) you can just set a flag on failure.

var failed = false;
var files = ['file1.txt', 'file2.txt'/*, ...*/];
files.forEach(function (file) {
  uploadFile(file).done(function () {
    if (failed) return;
    console.log('Successfully deployed ' + file);
  }, function () {
    if (failed) return;
    failed = true;
    console.log('Failed deployed ' + file);
  });
});
于 2013-10-19T11:36:45.603 回答