Refactor to use promises and handle errors