Reorganized code to be more readable with promises