Last active
August 29, 2015 14:07
-
-
Save jarrettmeyer/5cfc80c0862dc3862e73 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Load a collection of products from a data store. | |
* @param {array} productIds - Array of product IDs. | |
* @param {function} load - Function to load a product by ID, e.g. fetch from API, etc. | |
* @param {function} done - Done callback, to be fired when all products are loaded. | |
*/ | |
function loadProducts(productIds, load, done) { | |
// Set up vars that we will need in this function. | |
var numberOfProductIds = productIds.length; | |
var counter = 0; | |
var products = []; | |
// Loop through each product ID. Call the load function for each product ID. | |
// Load will return a product via a callback. | |
return productIds.forEach(function (productId, index) { | |
return load(productId, function (product) { | |
// Assign the product to the array. Increment the counter. If the counter | |
// is equal to the number of products, then everything has been loaded. | |
// Invoke the done callback. | |
products[index] = product; | |
counter += 1; | |
if (counter === numberOfProductIds) { | |
done(products); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment