0

I am looking for a way where in i can post multiple HTTP POST requests and just in case there is error on one or more of them then i can know which of those got the error.

I tried implementing many logic via observables but no success. Please suggest.

mansi
  • 1

1 Answers1

1

You could use Promises

for all requestItems {
    http.post(url, body).toPromise().catch(error => {
       // This request failed.
    })
}

or if you want to wait for all to finish, you can collect the promises to an array and then use

Promise.all(promises)
    .catch(error => ...)
    .then(results => ...);

as can be seen in Handling errors in Promise.all

Edit:

You can use Promise.all this way:

// Create an array of your promises
const promises = [...];
const resolvedPromises = [];
promises.forEach(promise => {
    // Collect resolved promises - you may return some values from then and catch
    resolvedPromises.push(promise
        .then(result => 'OK')
        .catch(error => 'Error')
    );
});
Promise.all(resolvedPromises).then(results => {
    // results contains values returned from then/catch before
    console.log('Finished');
})
Community
  • 1
  • 1
Ján Halaša
  • 8,167
  • 1
  • 36
  • 36
  • If you want to know which request threw exception catch them on individual promise level. Promise.all() will catch only the first one (all or nothing attitude). – borkovski Mar 30 '17 at 06:58
  • I can't catch errors on individual promise level, because i need to wait for all promises to finish and then find out which all errored out. Promise.all won't help either. – mansi Mar 30 '17 at 07:55
  • I added an example of Promise.all() usage. – Ján Halaša Mar 30 '17 at 09:22
  • @mansi have you tried the code I added? If it helped, please mark the answer as accepted, if not, let me know what's the problem with it. – Ján Halaša Mar 31 '17 at 07:56