I need help with a startWebRequest in a function

I am making a library and one of its functions is to take in a Pokemon name and output its Pokemon type. I am using startWebRequest that goes to the PokeApi and return its Pokemon type, however, the callback function is asynchronous and just returns ‘undefined’. Is there any way to fix this?

Here is the link: Code.org - App Lab

I see that you have studied the Pokemon API. I also see an advanced understanding of Javascript objects. Good work.

Are you familiar with the Scopion and the Frog fable? The Scorpion and the Frog - Wikipedia startWebRequest is the scorpion and you are the frog.

You must embrace the scorpion’s nature…wait…let me start over. You must embrace the way startWebRequest works and use it to your advantage.

One thing that might be helpful to visualize the problem is to look at your code without the callback:

function PokeType(name){
  var url = "https://pokeapi.co/api/v2/pokemon/" + name.toLowerCase().trim();
  startWebRequest(url, callBackGoesHere);
}

When we look at it like this we can see why it doesn’t do what you want. The code that runs doesn’t return anything at all. The callback does eventually run, but you don’t have any control over when. You also don’t know where it returns that value. There is no way to change that easily. If you try to wait for the callback to run with some kind of busy loop it will never run! Javascript only does one thing at a time and you need to stop your code to give that callback a chance to run.

So embrace the callback! Make your interface accept a callback of its own.

function PokeType(name, gotPokeTypeCallback){
  var url = "https://pokeapi.co/api/v2/pokemon/" + name.toLowerCase().trim();
  startWebRequest(url, function(status, type, content) {
    var jsonContent = JSON.parse(content);
    if(jsonContent.types.length == 2){
      gotPokeTypeCallback([jsonContent.types[0].type.name, jsonContent.types[1].type.name]);
    }else{
      gotPokeTypeCallback([jsonContent.types[0].type.name]);
    }
  });
}

PokeType("pikachu",function (types) {
  console.log(types);
});

What we have done here is added the parameter gotPokeTypeCallback. When the callback for startWebRequest runs we will make a call to gotPokeTypeCallback passing to it the Poke type. The program that uses this will use it just like you would any other function that takes a callback.

I see. Well, thank you for your help.