reema
reema

Reputation: 1

calling multiple https request inside express route in node js

1

I have route like this:

router.get('/test', async(req, res)=>{ });

i used to use request module to perform the http calls.

But now, I want to call multiple http calls and combine the responses into single JSON object

How to do it?

Upvotes: 0

Views: 177

Answers (1)

John Williams
John Williams

Reputation: 5430

With a method marked as async you can use the await keyword to make the http calls synchronous, ie wait for the resonse.

router.get('/test', async(req, res)=>{ 

    // first call    
    var result1 = await fetch('https://jsonplaceholder.typicode.com/users');
    var resultJson1 = await result1.json();
    var resultObject1 = JSON.parse(resultJson1);

    // second call    
    var result2 = await fetch('https://jsonplaceholder.typicode.com/posts');
    var resultJson1 = await result1.json();
    var resultObject2 = JSON.parse(resultJson2);

    var combinedResult = resultObject1.fieldName + resultObject2.anotherFieldName


 res.send(JSON.stringify(combinedResult));

});

Upvotes: 1

Related Questions