'Javascript exiting normal execution order
So I will attach my simplified code.
So when the page load the debugger follow the expected row order: 27->9->10
When I click on topNewsButton, the executing order should be 17->18
But the actual order is: 17->27->9->10.
I hope someone can help me. Thank you
7. let dom = {
8. init: function () {
9. dataHandler.getData("https://api.hnpwa.com/v0/news/1.json", (response) => {
10. dom.upload(response);
11. })
12. let topNewsButton = document.querySelector('#top-news');
13. topNewsButton.addEventListener('click', dom.loadNews);
14. },
15.
16. loadNews: function () {
17. dataHandler.getData("https://api.hnpwa.com/v0/news/1.json", (response) => {
18. dom.upload(response);
19. })
20. },
21.
22. upload: function (datas) {
23.
24. },
25. };
26.
27. dom.init();
As it works smoothly with rows 9, 10 I dont understand why it doesnt work with 17, 18. And the two rows are exactly the same.
18th line never executes. So I tried to with replacing the 18th line with alert("abc"); And there was no alert. Upon clicking topNewsButton only the loadNews() function should execute, shouldn't it? So how is the order 17->27 possible?
Here is the getData function
export let dataHandler = {
getData: function (url, callback) {
fetch(url, {
method: 'GET',
credentials: 'same-origin'
})
.then(response => response.json())
.then(json_response => callback(json_response));
},
}
Solution 1:[1]
Actually the problem was that I left a href="/" in the HTML of topNewsButton.
Solution 2:[2]
The code is executing in that order because requests take time to get responses, and the callbacks only get called after the responses are received.
So, on line 17, you send out a request. Line 18 (the callback) doesn't get executed yet because it the request was just sent and it therefore doesn't have a response yet. Then you call the init function on line 27. The first line of the init function is 9, where you send out another request. For whatever reason, that request gets a response first, so it calls its callback function on line 10 first. Eventually, when the line 17 request gets a response, it will call its callback on line 18.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | csizmaziagergely1 |
Solution 2 | EKW |