代码之家  ›  专栏  ›  技术社区  ›  Wolfdog

React Native Expo应用程序异步下载

  •  2
  • Wolfdog  · 技术社区  · 8 年前

    创建react本机应用程序 建立一个项目。正如你们可能知道的,当你们开发应用程序时,它使用Expo作为一个框架。

    我正在使用Expo的文件系统。downloadAsync()下载我需要的文件。我需要下载多个文件,所以我在里面运行这个命令。map(),如下所示:

    this.state.files.map(file => {
        FileSystem.downloadAsync(file.url, FileSystem.documentDirectory + file.name)
        .then(({ uri }) => console.log('Saved this file at: ' + uri))
        .catch(console.log('Error when downloading file.'))
    })
    

    现在与。then()我知道每个文件是什么时候下载的,但是我怎么知道所有文件是什么时候下载完毕呢?

    我可以让这个函数返回一个新的承诺吗?我认为这是一个正确的方法,但我不知道如何做到这一点?我应该把决心和拒绝放在哪里?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Evan Bacon    8 年前

    看起来你需要 Promise.all() ! 它将删除一个承诺数组,然后返回一个新的承诺,该承诺将在数组中的每个承诺返回结果后解析。

    如果你看这里的世博会文件 preloading and caching assets 你会看到一个很好的例子。

    async _loadAssetsAsync() {
      const imageAssets = cacheImages([
          'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',
          require('./assets/images/circle.jpg'),
      ]);
    
      const fontAssets = cacheFonts([FontAwesome.font]);
    
      // Notice how they create an array of promises and then spread them in here...
      await Promise.all([...imageAssets, ...fontAssets]);
    }
    

    在你的情况下,像这样的事情会奏效

    const assets = this.state.files.map(file =>
        FileSystem.downloadAsync(file.url, FileSystem.documentDirectory + file.name)
    )
    /// Here is where you put the try.
    try {
      await Promise.all(assets);
    } catch (error) {
      /// Here is where you would handle an asset loading error.
      console.error(error)
    }
    console.log("All done loading assets! :)");
    
    推荐文章