JS脚本中的执行顺序 [英] Execution order within JS script

查看:29
本文介绍了JS脚本中的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试创建一个从 API 实时获取信息的网站.为此,我现在尝试根据 API 调用更改变量.在玩弄 JS 代码时,我意识到执行顺序与预期不符.

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);

我不知道为什么它首先创建 console.log(a) 然后获取 API 请求.

I am not sure why it is creating the console.log(a) first and then gets the API request.

是否有可能我可以先运行 API 调用以使用 a 的修改值.

Is there a possibility where I can run the API call first in order to use the modified value of a.

对于包括 HTML 和 CSS 在内的所有代码,请查看我的 用于此项目的 Github 存储库.

For all the code including HTML and CSS have a look at my Github repo for this project.

推荐答案

fetch(url) is async.在 javascript 中,首先执行所有同步代码,然后在完成后 async 代码将在 事件循环.

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.

因为console.log(a);首先是同步的,这将被执行,然后是异步 promise.then().另请查看 promises 这是一个 Javascript有助于处理异步代码的构造.

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.

您也可以在 .then() 的 promise 中运行您的代码,如下所示:

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]);
})

这是另一个示例,说明如何在执行 Promise 期间影响变量.不过,需要了解 Promise 的工作原理:

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);
});

这篇关于JS脚本中的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆