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?
-
1A return in a callback other than a then() often has nowhere to return to. That is definitely true in this casecharlietfl– charlietfl2021年04月03日 12:01:14 +00:00Commented Apr 3, 2021 at 12:01
1 Answer 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;
}