0

Why is the value of i in getscore() (which is a callback to the second api) non-sequential which results in the undesired output of my application?

function getscore(sid, mid, callback) {
  fetch("https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=" + sid + "&matchid=" + mid, {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
        "x-rapidapi-key": "..."
      }
    })
    .then(response => {
      return (response.json());

    })
    .then(function(data2) {
      callback(data2);
    });
}
fetch("https://dev132-cricket-live-scores-v1.p.rapidapi.com/matches.php?completedlimit=6&inprogresslimit=7&upcomingLimit=9", {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
      "x-rapidapi-key": "..."
    }
  }).then((response) => {
    return response.json();
  }).then((MyJson) => {
      console.log(MyJson);
      for (let i = 0; i < MyJson.matchList.matches.length; i++) {
        //some opeerations
        console.log(i); //sequential
        getscore(matchid, function(data) { //callback second api
          console.log(i); //non-sequential
        });
mplungjan
  • 169,008
  • 28
  • 173
  • 236

2 Answers2

0

Your call to the getscore method is passing only 2 parameters in, your declaration calls for 3

GizmoZa
  • 106
  • 3
0

The problem is that the API is syncronous & you are trying to use it in asyncronous manner

You'll need your function getScore to return a promise & chain the promises in your loop to achieve this

function getscore(sid, mid) {
    return new Promise(resolve => {
        fetch(
            'https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=' + sid + '&matchid=' + mid,
            {
                method: 'GET',
                headers: {
                    'x-rapidapi-host': 'dev132-cricket-live-scores-v1.p.rapidapi.com',
                    'x-rapidapi-key': '...'
                }
            }
        )
            .then(response => {
                return response.json();
            })
            .then(function(data2) {
                resolve(data2);
            });
    });
}
fetch(
    'https://dev132-cricket-live-scores-v1.p.rapidapi.com/matches.php?completedlimit=6&inprogresslimit=7&upcomingLimit=9',
    {
        method: 'GET',
        headers: {
            'x-rapidapi-host': 'dev132-cricket-live-scores-v1.p.rapidapi.com',
            'x-rapidapi-key': '...'
        }
    }
)
    .then(response => {
        return response.json();
    })
    .then(async MyJson => {
        console.log(MyJson);

        await Promise.all(
            MyJson.matchList.matches.map(async val => {
                await getscore(matchid);
            })
        );
    });
Sarfraaz
  • 1,273
  • 4
  • 15