Skip to content

Instantly share code, notes, and snippets.

@ibratoev
Created April 19, 2018 13:53
Show Gist options
  • Save ibratoev/3723891d81b98b94f7dec04b979164ff to your computer and use it in GitHub Desktop.
Save ibratoev/3723891d81b98b94f7dec04b979164ff to your computer and use it in GitHub Desktop.
Async-await vs then with not well behaving functions
const shouldReturnPromise = () => { throw "test"; }
const withAsyncAwait = async () => {
try {
await shouldReturnPromise()
} catch (e) {
console.log('Handled: ' + e)
}
}
const withPromise = async () => {
shouldReturnPromise().then(null, () => console.log('Not Handled!'));
}
console.log(withAsyncAwait());
console.log(withPromise());
Copy link

ghost commented Apr 19, 2018

So, I reviewed our code and our request module from the core. The correct example should be:

const shouldReturnPromise = () => { return new Promise(() => { throw "test" }) }

const withAsyncAwait = async () => {
  try {
    await shouldReturnPromise()
  } catch (e) {
    console.log('Handled: ' + e)
  }
}

const withPromise = () => {
  shouldReturnPromise().then(() => console.log('toto')).catch(() => console.log('Not Handled!'));
}

console.log(withAsyncAwait());
console.log(withPromise());

Copy link

ghost commented Apr 19, 2018

And in this case, you actually catch with Promise: https://codepen.io/jacktheripper-the-sans/pen/vjEdqw

@ibratoev
Copy link
Author

In a perfect world it would not make a difference.
From what I've seen in reality, it is hard to make sure you always return promises and not throw errors without using async/await.

@ibratoev
Copy link
Author

I understand that this is corner case (hence the title with not well behaving functions) ;) But it just makes me feel safer using async/await.

Copy link

ghost commented Apr 19, 2018

Copy link

ghost commented Apr 19, 2018

They try-catch on their side, so no needs for one more I think

@ibratoev
Copy link
Author

My example was for the general discussion not for the particular case ;)

Copy link

ghost commented Apr 19, 2018

Yes, sure. But since the discussion has been running for the whole afternoon, I just wanted to make sure that we are aligned on how the current code behave and why try-catch wouldn't be required in that case because Promise.catch would have the same effect

@ibratoev
Copy link
Author

ibratoev commented Apr 19, 2018

Totally aligned 👍 The current code was moved from the Hype project. I would use async/await as I find it safer and simpler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment