Ironlors
Ironlors

Reputation: 193

Execution order within JS script

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.

Upvotes: 1

Views: 86

Answers (1)

Willem van der Veen
Willem van der Veen

Reputation: 36660

fetch(url) is async. In javascript first all synchronous code is executed then after this is finished the async code will be executed in the event loop.

Because console.log(a); is synchronous first this will be executed and after this the async promise.then(). Also take a look into promises which is a Javascript construct which helps to deal with async code.

You can run your code also in a .then() of the promises like this:

fetch(url)
.then(res => {
 a = 10;
 return res;
})
.then(res => res.json())
.then((out) => {
changeProvinceName(out.data[500071433][0]);
})

Here is another example of how you can influence a variable during the execution of a promise. A understanding of how promises work is required though:

let hey = new Promise((res, rej) => {
  res(5);
});

hey.then((res) => {
  res += 5;
  return res;
}).then((res) => {
  console.log(res);
});

Upvotes: 1

Related Questions