I have a class that handles data. Other classes can give it their values and the data class will populate them.
It looks like this:
class Data
constructor : ->
@products = null
populateProducts : (callback)=>
ajaxCall (data)=>
@products = data
callback()
allProducts : (list)=>
if @products?
list = @products
else
@populateProducts => allProducts list
The problem I am facing is that every method I add will have to check if products exists. So I am looking into ways to make that part of the code reusable.
One way I tried was the following:
productsCheck : (callback)=>
if @products?
callback()
else
@populateProducts => products callback
Using this method I could simplify allProducts:
allProducts : (list)=>
@productsCheck => list = @products
In the end I am looking for technique that does: “if products don’t exists populate them from the database”. I was maybe thinking that this might be a known pattern so if that is the case information about it is also appreciated.
Because you’re loading
@productsasynchronously, and every method on the object has to (potentially) wait for@productsto load, every method on the object is asynchronous and needs to return its result to a callback. There’s no way around this; you can’t make asynchronous JS code synchronous.allProductscan’t just return a value.Here’s what you should do: First, change
populateProductsso it won’t make an Ajax call if it doesn’t have to:Then just start each method that uses
@productswith a call to@populateProducts, like so: