Search code examples
node.jsapiasynchronousgetrequest

Using Responses from Get Requests to Create New Request


So, I am currently pulling from an API that gives a response like this.

{
  "meta": {
    "limit": 20,
    "next": null,
    "offset": 0,
    "previous": null,
    "total_count": 10
  },
  "objects": [
    {
      "date": "2019-03-15",
      "id": 16,
      "mSlug": "gud_vs_dex",
      "resource_uri": "/api/v1/match/16/",
      "team1": "/api/v1/team/7/",
      "team2": "/api/v1/team/3/",
      "time": "21:30:00",
      "viewLink": "twitch.tv/tectalparrot198q",
      "viewLink2": null
    },

I then need to be able to get five fields from this response - mSlug, team1, team2, date, and time. I have no problem getting mSlug, date, and time. However, the issue is that I need to use the links returned from team1 and team2 to make new GET requests, that return an API that looks like:

{
  "captain": "Parrayeet",
  "currentRanking": 100,
  "id": 7,
  "members": "CFE SilentHeart,GreenTigerBeast,Pack Jaul",
  "name": "Guardian Down",
  "platform": "Xbox",
  "resource_uri": "/api/v1/team/7/",
  "slug": "guardian_down"
}

From here, I need to be able to get the names of the teams that I am searching for. Finally, in the end, I need to be able to piece together the information from all of the calls to make one string telling the user the team's names (from the second/third calls), and the date/time/link from the first call. However, because the requests are asynchronous, I am unable to save these results to any variable or array, so I can't simply do a

slug = response.body.objects[0].mSlug

Are there any good ways that I can make multiple GET requests, with some using the response's information, and concatenate the data together at the end? I have tried using fetch, request, and request-promise, all to no avail. Any help (and explanation as to why this works) would help.


Solution

  • You can chain you promise like this:

    rp(options)
    .then(function (body) {
        idk(body.objects)
        return body     
    })
    .then(function (value) {
        // do something with value
        makeCall(value.objects)
        idk(body.objects)     
    })
    .catch(function (err) {
        console.log(err)
    });
    

    After your first promise resolves, you can use return to pass the value to the next .then method.