Async ... Await Concurrency In JavaScript Athman Gude
Concurrency Doing multiple tasks over a period of time (Generally order-independent or partially ordered units of work)
Concurrency is important when waiting on input/ output such as network requests, reading/ reading from disk or user input
Typically, programs wait for IO in two ways: - Blocking (Synchronous) - Easy to write - Uses multithreading - Memory and context-switching overhead - Non-blocking / event-loop (Asynchronous) - Single-threaded - High-concurrency with low memory consumption - Great for UI and IO-bound services rather than CPU bound
All modern JavaScript engines use the non-blocking/ event loop approach
So what happens if you block in JavaScript? There are a few things that will block - alert/ prompt/ confirm - Synchronous XMLHttpRequest - fs.readFileSync and file operation in Node
Blocking in the browser will halt everything, including all user interaction, even scrolling
Callbacks Just pass a function that will be called when the task is complete
Callbacks
Callbacks The good and the bad
The Promise Land Thin but powerful abstraction on top of callbacks. Solves several problems: - Easy chaining for sequential and parallel tasks - Error handling - Composable; can pass around a representation
It’s better, I promise In its basic form, it looks no better than callback style … but you actually get a lot more
But we are still putting callbacks inside .then() Can we do better?
But JavaScript is still single-threaded So we can’t block
However … There is a special thing called a “Generator Function” that can be paused
Promises + Generators = Awesome!
async … await
It’s a win We get back most of our traditional constructs - for/ while - try/ catch - Readable, sequential program flow - Powerful inter-op with promises
It’s just promises - An async function always returns a promise - When we await a promise, our function pauses until the promise is resolved - We can still use all our favorite promise helpers such as Promise.all()
Pro Tips - Don’t forget to await - Be careful about doing too much sequentially when you can actually do it in parallel - Using await in map/filter won’t do what you might expect! - Even though it looks synchronous, your code has been paused and resumed
(function() { console.log(thank y’all) })()

Async ... Await – concurrency in java script

  • 1.
    Async ... Await ConcurrencyIn JavaScript Athman Gude
  • 2.
    Concurrency Doing multiple tasksover a period of time (Generally order-independent or partially ordered units of work)
  • 4.
    Concurrency is importantwhen waiting on input/ output such as network requests, reading/ reading from disk or user input
  • 5.
    Typically, programs waitfor IO in two ways: - Blocking (Synchronous) - Easy to write - Uses multithreading - Memory and context-switching overhead - Non-blocking / event-loop (Asynchronous) - Single-threaded - High-concurrency with low memory consumption - Great for UI and IO-bound services rather than CPU bound
  • 6.
    All modern JavaScriptengines use the non-blocking/ event loop approach
  • 7.
    So what happensif you block in JavaScript? There are a few things that will block - alert/ prompt/ confirm - Synchronous XMLHttpRequest - fs.readFileSync and file operation in Node
  • 8.
    Blocking in thebrowser will halt everything, including all user interaction, even scrolling
  • 9.
    Callbacks Just pass afunction that will be called when the task is complete
  • 10.
  • 11.
  • 15.
    The Promise Land Thinbut powerful abstraction on top of callbacks. Solves several problems: - Easy chaining for sequential and parallel tasks - Error handling - Composable; can pass around a representation
  • 17.
    It’s better, Ipromise In its basic form, it looks no better than callback style … but you actually get a lot more
  • 21.
    But we arestill putting callbacks inside .then() Can we do better?
  • 23.
    But JavaScript isstill single-threaded So we can’t block
  • 24.
    However … There isa special thing called a “Generator Function” that can be paused
  • 27.
  • 28.
  • 30.
    It’s a win Weget back most of our traditional constructs - for/ while - try/ catch - Readable, sequential program flow - Powerful inter-op with promises
  • 33.
    It’s just promises -An async function always returns a promise - When we await a promise, our function pauses until the promise is resolved - We can still use all our favorite promise helpers such as Promise.all()
  • 35.
    Pro Tips - Don’tforget to await - Be careful about doing too much sequentially when you can actually do it in parallel - Using await in map/filter won’t do what you might expect! - Even though it looks synchronous, your code has been paused and resumed
  • 37.

Editor's Notes

  • #2 Today we’ll talk about concurrency in modern JavaScript Introduce myself My name is Athman Gude I am JavaScript and React Engineer
  • #3 Typically one core can only do one thing at any moment But over a period of time we want to do a number of things. For instance an API server wants to serve multiple requests from clients, a script wants to read multiple values from a database before it returns a response. What we are talking about is doing multiple things over a period of time and some of those things we can do in parallel and some we have to do one at a time sequentially Generally, order-dependent or partially ordered units of work is where concurrency happens.
  • #4 This is an example of concurrency In this example we see a number of different tasks that start at different times but are kind of running over the same duration of time in parallel This is something that is kinda hard to do in computing, in particular it’s hard to reason about, it leads to race conditions, it leads to different models of things changing over time
  • #5 Concurrency is particularly important when waiting on IO such as network requests, reading from or writing to sisk, user input etc. Actually anything that is considered an asynchronous kind of activity where the CPU need to wait for the user do something or where the it needs to wait for data to arrive from the user or the network
  • #6 Typically programs wait for IO in two ways Synchronous IO Synchronous IO is easy to write It’s what we see in languages like Ruby or PHP, Python and that’s what most web server-side technologies are doing In order for that that to work we need multithreading because if we stop one thread we need another thread to be able to continue working But it’s easy to write because you write everything sequentially However there is a memory overhead to that because every thread requires memory and also there is also context switching when the CPU switches between the threads In Asynchronous IO So Asynchronous IO is the other way to handle IO And that is the event loop style that is single threaded so everything runs on one thread meaning we cannot block the thread However we get high concurrency and also it uses less memory It’s really good for UI, User interaction stuff that’s where the browser uses the event loop And also good for IO bound services. Things that are reading a lot from networks or databases or disks But not so great on CPU bound work because anything that is using the CPU is going to prevent other things from happening So that’s a bit of the overview of the two patterns And JavaScript as you know it is ……………….. The later one. Yeah everything runs on one thread
  • #7 Actually most browsers and server side JavaScript engines like V8, Chakra and frameworks are event driven or non-blocking There are some exceptions to that Like historically some browsers like NetScape are said to have been multi-threaded
  • #8 So what happens if you block in JavaScript There are some things that will block the execution We have alert and family Synchronous style of XMLHttpRequest, I remember working with this way back before I learnt about jQuery. It was probably a mistake or at least it was a bad idea. It shouldn’t really be that way But this is rare and people don’t use it anymore We also have some stuff in Node world that are intentionally synchronous for various reasons
  • #9 I think the one that everyone is familiar with is the alert style that blocks everything that is happening The page puts a dialog up and everything pauses. You can’t interact with the page, can’t press a button. You can’t even scroll And that’s kind of a bad bad user experience
  • #10 So how do we write concurrent software without blocking Generally in Javascript we use callbacks and it’s pretty straight forward. We just pass a function and when a task is finished JavaScript will call our function. For instance on an onclick event, A network request When reading files so the file is read and when it’s done our function is called
  • #11 Here we are gonna read a file and when we are done we have our content Does anyone understand the callback style Basically every JavaScript code you have written
  • #12 So what are the pros and cons of callbacks? Pros With callbacks we get a pretty good low level abstraction for concurrency for Asynchronous actions They performant with low overhead since there is no context switching involved You can do almost any Asynchronous tasks with callbacks So What’s the downside Cons Doing things in sequence is hard. But doing things in parallel is even harder You give up constructs you are familiar with such as for/ while and try…catch and these are things that people come from a Python or PHP background for and almost any other language and they don’t understand how you cannot do these things Error handling is no so great. Well you have to check for this error parameter as things could always fail in the middle of a network request etc. Code readability goes downhill and applications become hard to maintain, we get callback hell It’s also challenging to test
  • #13 “What’s wrong with my code?” You see this stuff on Stack overflow every day Can anybody help this poor PHP programmer to debug this?
  • #14 Here we are taking three files and we want to find the total number of bytes for these three files callbacks they add complexity it's messy to chain them And we haven’t done any error checking here
  • #15 Same as before but done in parallel How do we know we are done because the answer might come back in any order
  • #16 We have talked about Callbacks and now let’s talk about promises They are basically an abstraction of a callback and gives us the chaining that we need when doing tasks sequentially i,e task1 then wait till it finishes then task2 … It gives us the helpers to do things in parallel and And gives us error handling And they are composable And the way a promise works is we can pass around a representation of a future value So a promise is an object that represents what the value will be when the operation finishes
  • #17 Here is how we would read a file using promises We see that we get a “then” and a “catch” which are super handy
  • #18 It’s better because we can do some chaining on that Error handling I know it doesn’t look that sexy but it’s better. I know
  • #19 Here is an example of chaining promises. More like setTimout() in Promise Land This might be a little bit more than callbacks but it’s not that amazing
  • #20 This is an example that gives us flow control with promises We are doing some thnigs in sequence while others can be done in parallel
  • #21 Error handling Just one catch at the very end catches them all
  • #22 We are still doing callbacks even though putting them inside then But we are still having to provide the functions Can we just have a normal sequential program like in other languages?
  • #23 Here is what we want Declare a promise, wait for it to resolve and get the result That would be lovely
  • #24 We can’t stop the program in the previous slide just like when we have alert then the whole application will freeze until the pronise is resolved
  • #25 Here’s where things start getting exciting. So we can pause just one function and not the entire program and be able to resume it later
  • #26 Here’s how it looks like Take note of the star and the yield Generators are not about Asynchronous or event loop but just about pausing stuff There needs to be something controlling the resuming Some function needs to resume this whenever the fetch has completed Generators are pretty complex But they are the only thing that allows this to work So what happens when we combine Promises with Generators?
  • #27 More examples on generators representing the whole set of integers Here the function count is not gonna do anything just by calling it until we request the first value Then it’s going to pause right there and until we request the next value
  • #28 This is what it’s been all about guys
  • #29 Finally we are here async … await Is basically a thin layer of syntax over Promises and Generators
  • #30 Here is how it looks like Instead of a function start we have this ASYNC function It’s really similar to the function star We use the keyword await before a promise and it always have to be that way Await will pause it in the middle of execution and let the event loop do other stuff and finally when the promise it resolved then the function is resumed This is the whole story about async … await
  • #31 Works with any promisified library
  • #32 The read file example Two things could go wrong here Read file could throw an exception in Async World but we will still catch it
  • #33 Here we take an html element and we want to move it to the right every frame
  • #34 Here’s where things start getting exciting. So we can pause just one function and not the entire program and be able to resume it later
  • #35 Fetch friends with promise.all We do the first two things sequentially But fetching friends is fetched in Parallel The function getUserFriends() returns a promise itself because it is async
  • #37 Probably the first program I wrote after Hello World in C