0

I want to build a website that uses the client to call an API with JavaScript. I didn't know how to do that so I googled and came across Jquery. Then I wrote my function that makes the request. It looked like the following:

async function makeRequest(url) {
  await $.getJSON(url, function (data) {
    console.log(data);
    return data;
  });
}

This works fine and the print statement prints the received data. But if I call this function from another function, it doesn't return anything. It comes out as undefined every time. An example:

document.addEventListener("DOMContentLoaded", async function () {
  var players = await makeRequest(
    "https://phijoto.ddns.net/Playtime/playtime.json"
  );
  console.log(players);
});

async function makeRequest(url) {
  await $.getJSON(url, function (data) {
    console.log(data);
    return data;
  });
}

If I run this, it prints out the received data through the second print statement but the first always gives back "undefined". What can I do about that?

1
  • 1
    A return in a callback other than a then() often has nowhere to return to. That is definitely true in this case Commented Apr 3, 2021 at 12:01

1 Answer 1

1

You have to return something from makeRequest.

Also: Don't mix callbacks and promises, at best it makes for confusing code.

async function makeRequest(url) {
  const data = await $.getJSON(url);
  console.log(data);
  return data;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.