javascript wait for synchronous function