Fixing race conditions with deferreds