【问题标题】:How do I make variables available across different javascript files when the variables are declared using async/await?当使用 async/await 声明变量时,如何使变量在不同的 javascript 文件中可用?
【发布时间】:2022-11-15 08:01:20
【问题描述】:
<html>
  <!-- ... (other page content) ... -->
  <script src="common.js"></script>
  <script src="homepage.js"></script>
</html>

在我网站的每个页面上,我都有一个 common.js 文件,用于存放每个页面上始终需要的内容。然后我有一个专门用于该页面的 js 文件。

我的问题是在 common.js 文件中声明的变量也需要在第二个 js 文件中访问,但我遇到了一些问题,因为脚本没有等待声明数据变量,这是不允许的在脚本的顶层使用 await 。

// common.js
let data;
async function get_data() {
  data = await fetch('/get-data').then(res => res.json())
  console.log(data) // works!!!
}
get_data();
console.log(data) // does not work!!!
// homepage.js
console.log(data) // does not work!!!

所以我要问的是如何让两个不起作用的console.log(data)调用起作用!

【问题讨论】:

  • window.data = await fetch('/get-data').then(res =&gt; res.json())

标签: javascript async-await


【解决方案1】:

创建一个解析为 data 的全局 Promise,然后在需要使用它时调用该 Promise 的 .then

// common.js
window.dataProm = fetch('/get-data').then(res => res.json());

dataProm
  .then((data) => {
    console.log(data);
  })
  // .catch(handleErrors);
// homepage.js
dataProm
  .then((data) => {
    console.log(data);
  })
  // .catch(handleErrors);

【讨论】:

    【解决方案2】:

    将生成的承诺分配给全局范围的变量。

    // common.js
    async function get_data() {
      const res = await fetch('/get-data');
      if (!res.ok) {
        throw res;
      }
      return res.json(); // return the data
    }
    
    // Assign to a variable
    const dataPromise = get_data();
    
    dataPromise.then(console.log);
    
    // homepage.js
    dataPromise.then(console.log); // why does everyone log everything ¯_(ツ)_/¯
    

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 1970-01-01
      • 2011-12-12
      • 2012-10-12
      • 2022-08-14
      • 2023-03-26
      • 2020-08-07
      相关资源
      最近更新 更多