Skip to content Skip to sidebar Skip to footer

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 wi

Solution 1:

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 = newPromise((res, rej) => {
  res(5);
});

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

Post a Comment for "Execution Order Within Js Script"