Skip to content

Instantly share code, notes, and snippets.

@marcosmapf
Last active January 25, 2020 07:22
Show Gist options
  • Save marcosmapf/0e3b5df8162ce2c2598c134e3469fd22 to your computer and use it in GitHub Desktop.
Save marcosmapf/0e3b5df8162ce2c2598c134e3469fd22 to your computer and use it in GitHub Desktop.
Asynchronously fetch data from iterable structure
/*
Receives an iterable structure containing { target, options } objects and calls fetch on each
Returns a Generator of Promises
*/
export default function* fetchFromIterable(data) {
for (const { target, options = {} } of data) {
yield fetch(target, options)
}
}
@marcosmapf
Copy link
Author

marcosmapf commented Jan 19, 2020

Example:

function* fetchFromIterable(data) {
	for (const { target, options = {} } of data) {
    		yield fetch(target, options)
	}
}

(function fetchFromIterableExample() {
	const data = [
		{
			target: 'https://picsum.photos/200/300',
			options: { method: 'GET', cache: 'default' }
		},
		{
			target: 'https://picsum.photos/200/300',
			options: {}
		},
		{
			target: 'https://picsum.photos/200/300'
		}
	]

	const fetchImages = fetchFromIterable(data )
	for (const promise of fetchImages) {
		promise
			.then(image => console.log("image response data: ", image))
			.catch(error => console.error("Error loading image : ", error))
	}
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment