Reputation: 79
I have recently been experimenting with MyJSON. I was trying to make a function that grabs from my database (so that I don't have to type long text every time I need to get it), when suddenly my page froze whenever I ran the code. Based off my debugging, it does not even run the code before freezing. Is this a bug with my IDE? If it helps, I am using repl.it with HTML/CSS/JS.
function submit() {
}
console.log("test test test");
function getJSON() {
console.log("beginning");
var out;
console.log("start");
$.get("https://api.myjson.com/bins/1fsm75", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
console.log(json);
out = json;
console.log(out);
});
while(out == undefined) {}
return out;
}
console.log("testarooni");
console.log(getJSON());
Upvotes: 0
Views: 94
Reputation: 709
It's freezing because of this line
while(out == undefined) {}
It looks like you're trying to go for the behavior of "Wait for the $.get method to finish, invoke it's call back and assign the out value before continuing."
However, Javascript is single threaded. That means that while it's looping through while(out == undefined) {}
, it's constantly looping it and never had a chance to execute the $.get's response.
What you need to do is to handle the Promise/Observable (I forgot which) that $.get returns.
Upvotes: 0
Reputation: 8579
In order to troubleshoot the issue you are facing I would suggest to check the network tab in your browser (in Google Chrome press F12 to bring it up), in order to understand if specifically the GET call performances.
I would also like to suggest, in any case, to perform the same call using async call. An async GET call would be preferred because it is non-blocking.
Here's an example of an async GET call to retrieve data from the Endpoint you provided:
<!DOCTYPE html>
<html>
<head>
<script>
async function getDataAsync() {
let response = await fetch('https://api.myjson.com/bins/1fsm75');
let data = await response.json()
return data;
}
getDataAsync()
.then(data => console.log(data));
</script>
</head>
<body>
</body>
</html>
Upvotes: 1