当阅读关于async
和await
的内容时,我注意到它几乎与生成器函数等价。请考虑《TypeScript深度探索》中的这个片段:
为什么最终成为“新功能”的原因是什么?在我看来,只需使用某些库中的“wrapToReturnPromise”函数就可以达到同样的效果,而不会增加JavaScript本身的复杂性。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!
注意:这与此问题有关,但我在这里询问的是“为什么”,而不是“如何”。我试图理解动机。
wrapToReturnPromise
很复杂(而且经常被错误地实现/过于天真),并且比必要的开销更大。使用await
的async function
可以更好地被引擎理解和优化。 - Bergi