Promise.

In my code, I use Promise.all() to run the code asynchronously after all the promises have been executed. Sometimes one promise fails, and I don't know why. I would like to know which promise fails. Passing a callback as the second parameter of the .then method does not help much, since I know that the promise is rejected, but not that the promise is rejected.

Stack tracing also does not help, since the first element is the Promise.all() error handler. The line number from the Error object passed to the first parameter of the second function passed to the try Promise.all() function is simply the line number of the line in which I write the line number.

Does anyone know how to find out which promise is rejected?

+6
source share
2 answers

You can use the onreject handler for each promise:

 Promise.all(promises.map((promise, i) => promise.catch(err => { err.index = i; throw err; }); )).then(results => { console.log("everything worked fine, I got ", results); }, err => { console.error("promise No "+err.index+" failed with ", err); }); 

In general, each rejection reason should contain sufficient information to identify the problem that you need to handle (or report).

+10
source

this shell will wait and return every result and / or deviation

the returned array will be objects

 { // this one resolved ok: true, value: 'original resolved value' }, { // this one rejected ok: false, error: 'original rejected value' }, { // this one resolved ok: true, value: 'original resolved value' }, // etc etc 

One caveat: this will cause ALL promises to allow or reject, rather than reject, as soon as the first rejection occurs

 let allresults = function(arr) { return Promise.all(arr.map(item => (typeof item.then == 'function' ? item.then : Promsie.resolve(item))(value => ({value, ok:true}), error => ({error, ok:false})))); } allresults(arrayOfPromises) .then(results => { results.forEach(result => { if(result.ok) { //good doThingsWith(result.value); } else { // bad reportError(result.error); } }); }); 
+1
source

Source: https://habr.com/ru/post/1014654/


All Articles