【发布时间】:2021-12-02 03:12:37
【问题描述】:
有人可以向我解释为什么这不符合我的预期吗?
我希望最后一个 console.log 在我的函数运行后运行,但它返回的是空长度字符串而不是实际日期。
这些是我要在函数调用后设置的变量。现在声明它们,以便全局设置范围。
var seasonStart = '';
var seasonID = '';
这个函数获取我的 json 数据。我在我的代码中声明了上面的 URL,它按预期返回所有内容。
async function getCurrentSeasonapi(url) {
//store response
const response = await fetch(url);
//store data in JSON
var data = await response.json();
//I tried to set the variables here but it didn't work so I tried using a separate function
setSeasonInfo(data);
}
上面调用的函数:
//set current season
function setSeasonInfo(data) {
seasonStart = data.seasons[0].regularSeasonStartDate;
seasonID = data.seasons[0].seasonId;
//this returns the correct date
console.log(seasonStart);
}
调用函数,所以我的变量应该在这个函数运行后正确设置
getCurrentSeasonapi(getCurrentSeasonURL);
//this is returning '' instead of the actual date set in the function
console.log(seasonStart);
我认为这是一个范围问题,但我不确定为什么。 这是我正在测试范围的示例。这就是我期望我的代码运行的方式:
var test = 1;
async function changeTest() {
test =100;
}
document.getElementById("first").innerHTML = test + `<br>` + 'Run Function:' + `<br>`;
changeTest();
document.getElementById("first").innerHTML += test
<html>
<body>
<p> testing JS execution</p>
<div id = 'first'>
</div>
</body>
</html>
【问题讨论】:
-
这不是范围问题。你在哪里
awaitgetCurrentSeasonapi(getCurrentSeasonURL) -
你最后一个异步测试的例子并不能证明这一点,因为它没有任何异步。
-
在第二个代码块(在变量之后)我设置了异步函数 getCurrentSeasonapi。这个块里面有等待
标签: javascript async-await scope