首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拥有数千个文件的DownloadFile正在阻塞应用程序接口。

问拥有数千个文件的DownloadFile正在阻塞应用程序接口。
EN

Stack Overflow用户
提问于 2019-08-21 22:30:26
回答 2查看 899关注 0票数 0

我正在用以下代码下载15019张JPG格式的图片:

代码语言:javascript
复制
for (const item of requestUrl) {
    const optios = {
        fromUrl: item.urlPath,
        toFile: item.path,
    };
    downloadFile(optios).promise;
}

❌应用程序接口被阻塞了

备注重要的:我知道RN只在一个线程上运行,所以我实现了运行在前台和后台的无头JS,它可以工作,但是在相同的行为下,接口是阻塞的。

有人能帮我解决这个问题吗?

react本机-fs“:"2.13.3

react原生: 0.59.9

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-22 01:26:26

api本机-fs在它的本机实现中完成了所有的工作,并通过react-本机桥公开了一个异步api。因此,在下载文件时,js线程大部分时间都是空闲的,并且不管js是在前台运行还是在后台运行。

实际发行

您的实现的实际问题是downloadFile将触发下载并立即返回承诺。因此,您的for循环将几乎立即运行所有15k迭代,在应用程序的本机部分启动15k并发下载。这可能足以减缓整个应用程序被屏蔽的任何设备的速度。

溶液

如果您需要下载许多文件,您应该实现某种队列和流水线,以限制并发下载的数量。(即使设备能够在没有问题的情况下处理15k并发下载,下载也受到可用带宽的限制。拥有~3并发下载可能就足以一直使用最大带宽。)

可能的流水线解决方案如下所示:

(未运行或测试下列代码)

代码语言:javascript
复制
/**
 * 
 * @param {item} The item to download
 * @param {item.urlPath} The url to download the item from
 * @param {item.path} The local path to download the item to
 * @returns the Promise returned by react-native-fs downloadFile
 */
const downloadItem = ({ urlPath, path }) => {
  const options = {
    fromUrl: urlPath,
    toFile: path
  }
  return downloadFile(options);
}

/**
 * 
 * @param {Array} Array of the items to download
 * @param {integer} maximum allowed concurrent downloads
 * @returns {Promise} which resolves when all downloads are done
 */
const downloadPipelined = (items, maxConcurrency = 3) => {
    // Clone the items Array because we will mutate the queue
    const queue = [...items];
    /**
     * Calling this function will
     * - donwload one item after another until the queue is empty
     * - return a promise which resolves if the queue is empty and
     *   the last download started from this workerFn is finished
     */
    const workerFn = async () => {
        while (queue.length > 0){
            await downloadItem(queue.shift()); 
        }
    }
    /**
     * starts maxConcurrency of these workers concurrently
     * and saves the promises returned by them to an array
     */ 
    const workers = Array(maxConcurrency).fill(workerFn());
    /**
     * will resolve when all worker promises have resolved
     * (all downloads are done)
     * reject if one rejects
     */
    return Promise.all(workers);
} 
票数 4
EN

Stack Overflow用户

发布于 2019-08-22 00:06:07

你在使用某种国家管理吗?复古,背景,复古-传奇/复古?您可以使用react本机-后台-下载程序尝试通过后台下载。

如果你使用的是redux和redux-saga,你可以使用叉下载它,所以它是非阻塞的。

另外,如果您正在下载图像并将其存储在道具或状态中,则可能是对下载的每一张图像进行重命名。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57599915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档