Calling multiple HTTP requests in a single HTTP request in Node.js

前端 未结 2 1422
余生分开走
余生分开走 2021-02-02 02:35

I am trying to call multiple URL in a single URL call and push it\'s json response in an array and send that array in response to the end user.

My code look like

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 03:09

    I suggest to use the async library.

    async.map(urls, http.get, function(err, responses){
      if (err){
        // handle error
      }
      else {
        res.send responses
      }
    })
    

    The snippet above will perform a http.get call for each of the urls in parallel, and will call your callback function with the results of all of the calls after all the responses were received.

    If you want to call the urls in series, you can use async.mapSeries instead. If you want to limit the number of concurrent requests you can use async.mapLimit.

提交回复
热议问题