Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore errors using async/await syntax in JavaScript Promise.all()

I am trying to run a for loop which queues a bunch of asynchronous requests. Once all the requests complete, independent of whether they resolve or reject, I want to then run some code. I am trying to take advantage of the async/await pattern, as it looks nicer. :)

This is what I am doing:

var promises = []
for ( item in list ) {
    prom = AsyncFunction( item )
    promises.push(prom)
}

await Promise.all(promises)

doMoreAfter()

However, some of the promises fail, and the second that happens Promise.all() fails aswell.

I want to simply ignore any failed promises, and have the next code run after all the promises have completed.

I found solutions like this.

Promise.all([a(), b(), c()].map(p => p.catch(e => e)))
  .then(results => console.log(results)) // 1,Error: 2,3
  .catch(e => console.log(e));

But it doesn't look like it works when trying to turn it into the async/await format.

await Promise.all(promises.map(p => p.catch(e => e)))

What am I missing?

like image 598
Shawn Tabrizi Avatar asked Nov 26 '17 01:11

Shawn Tabrizi


1 Answers

I feel like the best you can do is this:

var promises = [a, b, c];
promises = promises.map(p => p().catch(e => undefined));

values = await Promise.all(promises);
console.log(values);  // ["a", undefined, "c"]

https://jsfiddle.net/DerekL/h5Lmxaqq/

Or you can create an ignore function:

function ignore(promise){
    return promise.catch(e => undefined);
}

async function main(){
    var promises = [a(), b(), c()];

    var values = await Promise.all(promises.map(ignore));
    console.log(values);
}

https://jsfiddle.net/DerekL/mwkww7w9/

like image 63
Derek 朕會功夫 Avatar answered Oct 19 '22 02:10

Derek 朕會功夫