I am currently trying to create a website which gets its information live from an API. For this, I am now trying to change a variable based on the API call. while playing around with the JS code I realized, that the order of execution is not as expected.
var url = "https://api.worldoftanks.eu/wot/globalmap/clanprovinces/?application_id=bbdd3a54ffe280ff581db61299acab9c&clan_id=500071433&fields=province_id%2C+daily_revenue%2C+province_name%2C+revenue_level";
var a = 10;
fetch(url)
.then(res => res.json())
.then((out) => {
changeProvinceName(out.data[500071433][0]);
})
.catch(err => { throw err });
function changeProvinceName(json){
console.log(json.province_name);
document.getElementById("province_name1").innerHTML = "<h2>"+json.province_name+"</h2>";
province=""+json.province_name;
a = 20;
}
console.log(a);
I am not sure why it is creating the console.log(a) first and then gets the API request.
Is there a possibility where I can run the API call first in order to use the modified value of a.
For all the code including HTML and CSS have a look at my Github repo for this project.
fetch()is asynchronous. It starts the operation and returns immediately. The functions passed to.then()will be called when the HTTP request completes..thenhappens after the request completes, while everything outside the.thenhappens while the request is happening. this is what makes asynchronous code able to be non blocking..then()callback (or by calling other functions from there).