Upgrade to Pro — share decks privately, control downloads, hide ads and more …

From Callback To Async Await

From Callback To Async Await

Tamar Twena-Stern

April 02, 2020
Tweet

More Decks by Tamar Twena-Stern

Other Decks in Programming

Transcript

  1. Tamar Twena-Stern • Software Engineer - manager and architect •

    BackEnd Team Leader @XM Cyber • Was a CTO of my own startup • Passionate about Node.js ! • Twitter: @SternTwena
  2. Problems •CPU and memory resources location for every new thread

    and performs context switching •On stressed – Context switching over actual work
  3. Asynchronous Programming • Synchronous activities will block the event loop.

    • Asynchronous programming has evolved in JavaScript • Functions are first class citizens • No return values, only function calls.
  4. Different To Implement Control Flows • Very hard to implement

    control flow patterns • You want to be able to execute tasks in : • Series • Parallel • Even implementing array mapping using pure asynchronous functions very hard with plane callbacks
  5. What Is A Promise • A proxy for a value

    that we don’t know yet • Register an event handler to • Success of an asynchronous operation • Failure of an asynchronous operation • Enable an asynchronous method to return value like a synchronous method
  6. Promise Libraries • Native in ES6 • Bluebird – add

    a lot of extra functionality on native ES6 • Promise.mapSeries() • Promise.reduce() • Promise.map() • Promise.Some() • Promise.any() • Promise.each() • Etc …
  7. What Is An Async Function • Return an Promise •

    Inside an async function, we can : • Use await before a function that returns a promise • Await waits for the promise to be resolved • Handle errors with easy and popular mechanism – try / catch • Behind the scenes – asynchronous code
  8. Await Keyword • Reserved word from ES7 • Can be

    used only inside an Async function • Await is used to wait for a promise • Await cause the execution of the function to stop • Same concept as generators • Help simplify the code to look synchronous • Behind the scenes – asynchronous code
  9. Concise And Clean • No need to use .than •

    No need to write anonymous callback function for .than or for .catch • Not creating variables that we will not need • Avoid nesting • Very intuitive
  10. Watch Out • The code is very concise and clean

    • This is miss-leading as the biggest advantages of Node.js are • Non blocking IO • Parallel IO work with the worker thread pool • You have to remember to work as much in parallel as you can!