javascript - Why do Promises capture syntax errors? -


why native promises act try/catch when comes syntax errors?

promises have value in flow control when need perform number of async operations in order. necessity of having implement own inadequate error handing implementations every promise makes them hassle work with.

take following code:

asdf    let 1 = new promise((resolve, reject) => {    asdf  }).catch(err => {    console.log(err)    console.log(err.stack)  })

the first syntax error produces typical browser error , stack trace 18 entries. promise'd version has 4.

so question why, when writing spec , implementing natively, did retain try/catch functionality of userspace implementation of promises used flow control leave standard error handling?

an actual syntax error thrown javascript parser when code loads , still thrown exception. when parser decides can't parse code, there's nothing else @ point. give , stop parsing rest of code.

it runtime errors (that happen during code execution not during loading/parsing) promises handle.

by specification, .then() promise handlers "throw safe" means turn thrown exceptions rejected promises. done because these handlers asynchronous , thrown exceptions in asynchronous callbacks useless because can't caught calling code since calling code no longer on stack , calling code can notified via callbacks. exceptions end going asynchronous infrastructure no calling code can intercept or handle them. so, made decision turn exceptions rejection normal reject handling , error propagation promises have can used.

and, because exceptions can't caught calling code, if promises didn't this, you'd have own try/catch in pretty every .then() handler make sure caught going wrong. so, saves lot of code , makes easy make sure asynchronous exceptions caught , error propagated calling code.

in nutshell, once used it, it's incredibly useful , since exception goes useless anyway, i'd designers made choice deciding catch exceptions , make them useful. fyi, can still own try/catch inside .then() handler , whatever want if desire.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -