shayy
shayy

Reputation: 1312

Handling an array of promises

I have a function which uploads a file to a server and returns a promise. I'd like to check when each promise finishes and display a log of "Successfully deployed filename..".

I don't care about the order of the promises, But Q.all() doesn't help me since it returns only when all of the promises finished or failing fast when one failed.

I'd like to write something that checks whenever one of my promises finish and displays the log. Since each file can be large, I want to user to be alerted what has been uploaded thus far.

When one of my files fails, the user will see something like:

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

Upvotes: 0

Views: 140

Answers (2)

ForbesLindesay
ForbesLindesay

Reputation: 10712

@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);
  });
});

Upvotes: 0

kamituel
kamituel

Reputation: 35960

Why not simply loop over your files (or promises)?

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);
  });
});

Upvotes: 3

Related Questions