【问题标题】:How does variable setting work with await?变量设置如何与等待一起工作?
【发布时间】: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


【解决方案1】:

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

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>

【讨论】:

  • 这种有道理。我可以看到我的例子哪里错了。我想我的问题更多是为什么我的代码与示例的工作方式不同?我尝试将您的修复应用于我的示例到我的实际代码,但它仍然返回''
  • 所以你做了await getCurrentSeasonapi(getCurrentSeasonURL);?
  • 又试了一次,现在可以正常工作了。我想当我早些时候尝试时我改变了其他东西。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多