refactor of migration code to fix some asynchronous issues