变量设置如何与 await 一起工作?

How does variable setting work with await?

有人可以向我解释为什么这不符合我的预期吗?

我期待在我的函数 运行 之后的最后一个 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);
}

调用函数,所以我的变量应该在这个函数之后正确设置 运行s

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>

您没有在等待电话。示例代码中应该有一个承诺。

var testSync = 1;
var testAsync = 1;
async function changeTest() {
  testSync = 100;
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      testAsync = 100;
      resolve();
    }, 300);
  });
}

document.getElementById("first").innerHTML = `${testSync} - ${testAsync} <br> Running <br>`;
changeTest();
document.getElementById("first").innerHTML += `${testSync} - ${testAsync}`
<html>

<body>
  <p> testing JS execution</p>

  <div id='first'>
  </div>


</body>

</html>

现在等待呼叫

var testSync = 1;
var testAsync = 1;
async function changeTest() {
  testSync = 100;
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      testAsync = 100;
      resolve();
    }, 300);
  });
}


(async function() {
  document.getElementById("first").innerHTML = `${testSync} - ${testAsync} <br> Running <br>`;
  await changeTest();
  document.getElementById("first").innerHTML += `${testSync} - ${testAsync}`
}());
<html>

<body>
  <p> testing JS execution</p>

  <div id='first'>
  </div>


</body>

</html>