Refactored code using Q library for asynchronous programming with promises.