Improved wait function should be faster and handle error logic more cleanly