Oracle Magazine, Jan/Feb 2018
Database Developer OPEN SOURCE Though interesting returning promises isnt what makes async functions special You could after all return promises from regular functions What makes async functions ORACLE MAGAZINE JANUARY FEBRUARY 2018 62 special is await await The await operator which is available only inside an async function is as close to magic as youll get in JavaScript Its like hitting the pause button on your code so that it can wait for a promise to be resolved or rejected before continuing This is a concept known as a coroutine Coroutines have been available in JavaScript since generator functions were introduced but async functions make them much more approachable Using await will not block the main thread Instead the currently running call stack up to the point of await will be completed so that other functions in the callback queue can be executed When the promise is resolved or rejected the remaining portion of the code is queued for execution If the promise was resolved its value is returned If the promise was rejected the rejected value is thrown on the main thread Heres a demonstration of await that uses setTimeout to simulate an async API Ive added some additional console output to help illustrate whats happening function getRandomNumber return new Promise function resolve reject setTimeout function const randomValue Math random const error randomValue 8 true false if error reject new Error Ooops something broke
You must have JavaScript enabled to view digital editions.