used $.when for waiting to run function until fetch loop is done