簡體   English   中英

在 React 中與 Promise 和異步函數作斗爭

[英]Struggling with promises and async functions in React

我正在做一個 React 項目,我有一個 function 遞歸地獲取分頁數據。 This function is defined in another function, where I activate the loading screen with showLoading() at the start, where I'm calling the fetching data function in the body and deactivate the loading screen with hideLoading() at the end. function:

const fetchPlaylist = (playlistId) => {
    showLoading()
    const getPlaylistDataRecursively = (url) => {
      fetch('/spotify/get-track-ids', {headers: {
        'url': url
      }})
      .then(response => response.json())
      .then(data => {
        console.log(data)

        setTitles(data.title)
        setArtists(data.artist)
        setFeatures(data.features)
        setIds(data.track_ids)

        if (data.next_url) {
          const next_url = data.next_url.replace('https://api.spotify.com/v1', '')
          getPlaylistDataRecursively(next_url)
        }
      })
    }
    getPlaylistDataRecursively(`/playlists/${playlistId}/tracks/?offset=0&limit=100`)
    hideLoading()
  }

我相信我可以使用then關鍵字將 promise 附加到 getPlaylistDataRecursively 調用,但我得到一個TypeError: Cannot read property 'then' of undefined 可能是因為 getPlaylistDataRecursively 不返回任何內容。 如何確保在hideLoading完成后調用 hideLoading?

您始終需要return promise。

const fetchPlaylist = (playlistId) => {
    showLoading()
    const getPlaylistDataRecursively = (url) => {
      return fetch('/spotify/get-track-ids', {headers: {
        'url': url
      }})
      .then(response => response.json())
      .then(data => {
        console.log(data)

        setTitles(data.title)
        setArtists(data.artist)
        setFeatures(data.features)
        setIds(data.track_ids)

        if (data.next_url) {
          const next_url = data.next_url.replace('https://api.spotify.com/v1', '')
          return getPlaylistDataRecursively(next_url)
        }
      })
    }
    return getPlaylistDataRecursively(`/playlists/${playlistId}/tracks/?offset=0&limit=100`)
      .then(() => hideLoading());
  }

或者,使用異步/等待:

const fetchPlaylist = async (playlistId) => {
    showLoading()
    const getPlaylistDataRecursively = async (url) => {
      const response = await fetch('/spotify/get-track-ids', {headers: {
        'url': url
      }})
      const data = response.json()
      console.log(data)
      setTitles(data.title)
      setArtists(data.artist)
      setFeatures(data.features)
      setIds(data.track_ids)
      if (data.next_url) {
        const next_url = data.next_url.replace('https://api.spotify.com/v1', '')
        await getPlaylistDataRecursively(next_url)
      }
    }
    await getPlaylistDataRecursively(`/playlists/${playlistId}/tracks/?offset=0&limit=100`)
    hideLoading()
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM