J
J
jeruthadam2017-09-02 18:43:17
JavaScript
jeruthadam, 2017-09-02 18:43:17

How to make multiple parallel queries and return 1 result?

It is necessary to execute axios several parallel requests and return the overall result. There is a code, but it returns the result from only one of the requests (after each refresh, randomly, then from one, then from the other)

app.get('/pets', (req, res) => {

    async.parallel({

      cat: function (callback) {
        axios('http://localhost:3001/cat')
        .then((response) => {
          callback(response.data)
        })
        .catch((err) => {
          callback(err)
        })
      },

      dog: function (callback) {
        axios('http://localhost:3002/dog')
        .then((response) => {
          callback(response.data)
        })
        .catch((err) => {
          callback(err)
        })
      }
    },

    function(results, error) {
      res.json({
        results: results,
        error: error
      })
    })
  })

In addition to axios, the async. How to do it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artyom Egorov, 2017-09-02
@jeruthadam

const cat = axios('http://localhost:3001/cat').then(res => res.data);
const dog = axios('http://localhost:3002/dog').then(res => res.data);
Promise.all([cat, dog])
.then(pets => console.log(pets))
.catch(error => console.log(error));

N
Negwereth, 2017-09-02
@Negwereth

Promise.all

A
Anton, 2017-09-02
@SPAHI4

const [{ data: cat }, { data: dog }] = await Promise.all([
   axios('http://localhost:3001/cat'),
   axios('http://localhost:3002/dog'),
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question