【问题标题】:How do I use the variable out of its asynchronous function scope如何在其异步函数范围之外使用变量
【发布时间】:2021-02-06 21:29:50
【问题描述】:

我需要使用我在该范围之外的异步函数中声明的变量。这可能吗?

movies.forEach((movie) => {
    const { title, poster_path, vote_average, overview, release_date, id } = movie

    async function getCredits(url) {
        const res = await fetch(url)
        const data = await res.json()

        const directors = [];
        
        const directorsName = directors.join(", ") // The one I want to bring out of its scope
    }

    const CREDITS_URL = `the credits url goes here and it uses this -> ${id}`
    getCredits(CREDITS_URL)

    const directorsName = directors.join(", ") // Like this

    const card = document.createElement("div")
    card.innerHTML = `
        <div class="director">
                <h3>Directed by ${directorsName}</h3> // This is where I need the variable
        </div>
    `
    cards.appendChild(card)
})

【问题讨论】:

    标签: javascript variables asynchronous scope


    【解决方案1】:

    可以从您的async 函数返回一些内容。您可以将您的 getCredits 函数移出循环,并制作循环 async,类似于:

    async function getCredits(url) {
      const res = await fetch(url)
      const data = await res.json()
      const directors = [];
      // Do something with data?
      
      return directors.join(", ");
    }
    
    movies.forEach(async (movie) => {
      const { id } = movie
    
      const CREDITS_URL = `the movie url goes here and it uses this -> ${id}`
      const response = await getCredits(CREDITS_URL);
    
      const card = document.createElement("div")
      card.innerHTML = `
          <div class="director">
                  <h3>Directed by ${response}</h3> // This is where I need the variable
          </div>
      `
      cards.appendChild(card)
    });
    

    【讨论】:

      【解决方案2】:

      如果您希望更快地创建 DOM 并“延迟加载”导演姓名,您可以执行以下操作:

      movies.forEach((movie) => {
        const { title, poster_path, vote_average, overview, release_date, id } = movie;
      
        const card = document.createElement('div');
        card.innerHTML = `<div class="director">
                <h3>Directed by <span class='dname'>...</span></h3>
              </div>`;
        const dname = card.querySelector('.dname');
      
        async function getCredits(url) {
          const res = await fetch(url);
          const data = await res.json();
      
          const directors = [];
      
          dname.textContent = directors.join(', ');
        }
      
        const CREDITS_URL = `the credits url goes here and it uses this -> ${id}`;
        getCredits(CREDITS_URL);
      
        cards.appendChild(card);
      });
      

      在这里,您正在创建 div 并立即附加它,但使用 ... 表示导演姓名。但是您将该部分放在一个跨度中,然后在 getCredits 解析后设置该跨度的 textContent。

      *编辑:这还有一个额外的好处,就是通过不使用 innerHTML 插入 HTML 来防止导演返回的 HTML 注入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多