0

I'm a bit confused about promises in javascript and the resolve() statement. I have this code

this.fetchRuns("https://www.speedrun.com/api/v1/runs?game=" + game_id).
then(() => console.log("abc"));

fetchRuns(url, max);
{
  return new Promise((resolve, reject) => {
    if (this.runs.length >= 100) return resolve();
    fetch(url)
      .then((data) => data.json())
      .then((json_obj) => {
        json_obj["data"].forEach((element) => {
          this.runs.push(element);
        });
        if (json_obj["pagination"]["links"].length == 0) return resolve();
        else {
          if (json_obj["pagination"]["links"].length == 1)
            resolve(this.fetchRuns(json_obj["pagination"]["links"][0]["uri"]));
          else resolve(this.fetchRuns(json_obj["pagination"]["links"][1]["uri"]));
        }
      });
  });
}

When I recursively call the function again, I need to use resolve() so that console.log("abc") gets called. I want to know the reason why.

My own thought is that every promise needs to be resolved so that then() will be called and when I don't use resolve() in the recursive call then the promise doesn't get resolved. Am I right with that?

DasEvoli
  • 55
  • 4
  • You shouldn't create a `new Promise` to begin with. Just return the one you got from `fetch`. – tkausl Jul 01 '22 at 10:18
  • @tkausl you are correct. I missed that. – DasEvoli Jul 01 '22 at 10:25
  • @tkausl the problem I have now is that I can't use then() to wait until all recursions are finished. So that console.log("abc") is only called after all recursions have finished. – DasEvoli Jul 01 '22 at 10:30
  • Then you're breaking the chain somewhere. – tkausl Jul 01 '22 at 10:33
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! Just `return` the promises that the recursive calls return so that [`then` can chain them](https://stackoverflow.com/a/22562045/1048572) – Bergi Jul 01 '22 at 12:28
  • "*when I don't use resolve() in the recursive call then the promise doesn't get resolved.*" - yes, that's correct. When you don't resolve the promise, the `then` handlers won't get called. – Bergi Jul 01 '22 at 12:29

0 Answers0