如何使用Expo在React-Native应用上顺序运行异步功能

Working on an assignment for a react native app using expo-av library for Sound files. Right now, the app has a startMusic function set in a Context file that is responsible for playing the app's background music. It only has one song for now:

const startMusic = async () => {
    try {
      await mainTheme.loadAsync(require("../assets/sounds/Katsu.mp3"))
      await mainTheme.playAsync()
      setSoundObject(mainTheme)
      console.log("The first song is playing! Enjoy!")
    } catch (error) {
      console.log(`Couldnt load main theme: ${error}`)
      return
    }
  }

像这样在主屏幕组件的文件中使用它:

const { startMusic } = useContext(MusicContext)

useEffect(() => {
  startMusic()
}, [])

对于第二首歌曲,我在MusicContext文件中编写了另一个const:

const secondSong = async () => {
    try {
      await mainTheme2.loadAsync(require("../assets/sounds/MainTheme2.mp3"))
      await mainTheme2.playAsync()
      setSoundObject(mainTheme2)
      console.log("Now playing the second track. Enjoy!")
    } catch (error) {
      console.log(`Could not play the second song: ${error}`)
      return
    }
  }

Annnnnd ...这就是我的麻烦所在。我知道这是行不通的,但我在组件文件中编写了此代码,以尝试让第二首歌播放在第一首歌之后

useEffect(() => {
    startMusic()
      .then(secondSong())
  }, [])

我知道还有更多,但是我遇到了麻烦。读了几个小时的文档有点让我的大脑瘫痪了。

无论如何,在此先感谢所有对有抱负的开发人员的帮助。

评论