A
A
Aleksandr2018-06-26 06:47:33
JavaScript
Aleksandr, 2018-06-26 06:47:33

How to make multiple requests in node.js?

There is an array with user IDs. It is necessary to get the data of these users through the site API. I do it this way:

const request = require(`request-promise`);
let ids = [2113811902, 2113811976, 2112091110 /* , ... */];

Promise
    .all(ids.map(id => {
        return request
            .get(`http://site.com/api/user/${id}`)
            .then(user => {
                return user;
            })
            // Что бы Promise.all обработал все запросы
            // обрабатываем ошибку каждого запросы
            // и возвращаем результат с ошибкой
            // и с ID, с которым была ошибка
            .catch(error => {
                return {
                    error: error.message,
                    userId: id
                };
            });
    }))
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.error(error.message);
    });

Am I using the correct approach? How to do it better?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question