When reading about async
and await
, I noticed that it's almost an equivalent of generator functions. Consider this fragment from TypeScript Deep Dive:
Async Await
(...)
// Not actual code. A thought experiment async function foo() { try { var val = await getMeAPromise(); console.log(val); } catch(err) { console.log('Error: ', err.message); } }
(...)
Generated JavaScript
You don't have to understand this, but it's fairly simple if you've read up on generators. The function
foo
can be simply wrapped up as follows:const foo = wrapToReturnPromise(function* () { try { var val = yield getMeAPromise(); console.log(val); } catch(err) { console.log('Error: ', err.message); } });
where the
wrapToReturnPromise
just executes the generator function to get thegenerator
and then usegenerator.next()
, if the value is apromise
it wouldthen
+catch
the promise and depending upon the result callgenertor.next(result)
orgenertor.throw(error)
. That's it!
What is the reason that it ended up being "a new feature"? IMHO just using that wrapToReturnPromise
function from some library would be just as good, while not contributing to the complexity of JavaScript itself.
Note: it's related to this question, but here I'm asking about the "why", not the "how". I try to understand the motivations.