繁体   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