Created
February 11, 2016 19:43
-
-
Save pr1ntr/623a9e8255750f5f9116 to your computer and use it in GitHub Desktop.
Image Sequence Loader using a Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from './http'; | |
const mapLoadImage = src => loadImage(src); | |
function loadImage(src) { | |
return new Promise((r, f) => { | |
let image = new Image(); | |
let passThroughTimeout = setTimeout(() => { | |
r(image); | |
},20000); | |
image.onload = function() { | |
clearTimeout(passThroughTimeout); | |
r(image); | |
}; | |
image.error = function() { | |
clearTimeout(passThroughTimeout); | |
console.warn('[Image] SRC:', src, 'Failed to load'); | |
r(image); | |
}; | |
image.src = src; | |
}); | |
} | |
function loopAsyncRecursive(it, allResults = []) { | |
const yieldResult = it.next(); | |
if (yieldResult.value instanceof Promise ) { | |
return yieldResult.value.then((results) => { | |
return loopAsyncRecursive(it, results).then((newResults) => { | |
return allResults.concat(newResults); | |
}); | |
}).catch(e => console.error('[imageSequenceLoader]: Error' , e)); | |
} else { | |
return Promise.resolve(allResults); | |
} | |
} | |
function* loadBlocks(blocks) { | |
for (let i = 0; i < blocks.length; i++) { | |
const block = blocks[i]; | |
const chain = block.map(mapLoadImage); //its ok | |
yield Promise.all(chain); | |
} | |
} | |
export default function({cdnRoot, dataUrl, concurrent = 5}) { | |
console.log('do it'); | |
return http(`${cdnRoot}${dataUrl}`).then(payload => { | |
let map = []; | |
const images = payload.images; | |
for (let i = 0; i < images.length; i += concurrent) { | |
map.push(images.slice(i, i + concurrent)); | |
} | |
return loopAsyncRecursive(loadBlocks(map)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment