A
A
alexmoran2017-03-23 11:17:45
JavaScript
alexmoran, 2017-03-23 11:17:45

Array Promise exception handling?

Good afternoon.
There is an array of promises, you need to execute them in parallel (asynchronously). How can I do that?
let arr = [new Promise[pending],new Promise[pending],new Promise[pending]
One solution I found was Promise.All([arr]). But some promises are fulfilled with reject, and Promise.All works if promises resolve.
For example I have an array Promise of

const cmd = require('node-cmd-promise');
let promisesArray = []
let array = ['google.ru', 'yandex.ru', 'habrahabr.ru', 'yana.ru']
for (let i = 0;i < array.length; ++i) {
    promisesArray.push(cmd(`ping ${array[i]}`));

}
console.log(promisesArray)
Promise.all(promisesArray).catch((error) => console.log(error)).then(results => console.log(results))

but it may not work because one of the promises will reject if the address is not pinged.
How to make all promises work, and process those that did not work in catch?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2017-03-23
@k12th

Did something similar recently. Something like this:

const cmd = require('node-cmd-promise');

const array = ['google.ru', 'yandex.ru', 'habrahabr.ru', 'yana.ru']

const promisesArray = array.map((url) => {
    return cmd(`ping ${array[i]}`)
        .then((pingResult) => Promise.resolve(pingResult))
        .catch(error => {
            console.error(error);
            return Promise.resolve(null);
        })
});

Promise.all(promisesArray).then((result) => {
    const finished = result.filter(result => result !== null);
    console.log('succesfully pinged: ', finished);
})

The idea is to catch the rejected promise and return Promise.resolve with some value instead.
Perhaps there is some more elegant option, but I never thought of it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question