forked from kfiroo/react-native-cached-image
-
Notifications
You must be signed in to change notification settings - Fork 83
/
ImageCachePreloader.js
48 lines (42 loc) · 1.28 KB
/
ImageCachePreloader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
const _ = require('lodash');
function createPreloader(list) {
const urls = _.clone(list);
return {
next() {
return urls.shift();
}
};
}
function runPreloadTask(prefetcher, imageCacheManager) {
const url = prefetcher.next();
if (!url) {
return Promise.resolve();
}
// console.log('START', url);
return imageCacheManager.downloadAndCacheUrl(url)
// allow prefetch task to fail without terminating other prefetch tasks
.catch(_.noop)
// .then(() => {
// console.log('END', url);
// })
// then run next task
.then(() => runPreloadTask(prefetcher, imageCacheManager));
}
module.exports = {
/**
* download and cache an list of urls
* @param urls
* @param imageCacheManager
* @param numberOfConcurrentPreloads
* @returns {Promise}
*/
preloadImages(urls, imageCacheManager, numberOfConcurrentPreloads) {
const preloader = createPreloader(urls);
const numberOfWorkers = numberOfConcurrentPreloads > 0 ? numberOfConcurrentPreloads : urls.length;
const promises = _.times(numberOfWorkers, () =>
runPreloadTask(preloader, imageCacheManager)
);
return Promise.all(promises);
},
};