What's a Closure?

  1. What's a Closure?
  2. Variables and Values
  3. Defining Functions
  4. Side Effects
  5. Functions are Values
  6. Returning Functions
  7. Function Scope
  8. Nested Functions
  9. Stateful Closures
  10. Private Data
  11. Asynchronous Callbacks
  12. Continuation Passing

Asynchronous Callbacks

Sometimes functions can take a long time to return. For example if you call a function read(file), the function might have to stop and wait for the disk to spin-up and seek to the right location before the information is ready. If the file is actually a socket connection to another server in the cloud, the function will have to wait until the other server responds.

This can be a problem. For example, in the browser you don't want the user interface to freeze while you fetch map results from Google Maps. On the server, you don't want one request that accesses a rarely used part of the database to hold up all other requests.

Luckily there is a solution. In the asynchronous model the readAsync function accepts both a file and a callback parameter. The function returns immediately before the file is read and schedules the read to happen sometime in the future. Once the data is ready, the callback function is called on the data.

And what's a callback? It's a closure! We'll look at how to use asynchronous functions; implementing them is a whole other story.

Here's an example of how you would use a regular blocking read function to get the contents of a file.

Here's the same example using an asynchronous readAsync function.

Someone calls readFileAsync. Inside readFileAsync, readAsync is called with callback func. Once the data is ready, readAsync calls func with the data. Then func calls doSomething with the updated string containing the data. This might happen before, during, or after the execution of doMoreStuff().

Writing programs that use asynchronous callbacks can feel a bit inside-out. It can help to use anonymous functions. Here's the previous example with an anonymous function.

Here's an example that uses the asynchronous function writeAsync(file, contents, callback). In this case the callback doesn't take any arguments, it is just called once the write finishes.

Because doMoreStuff is in the callback, we know that it will only be called once the write is finished.

Define a function named doStuffAsync that takes one argument callback. Your function should read the contents of file "passwords", write the result to file "world.txt" along with the extra text "OWNED", then call callback with no arguments. Use both the asynchronous readAsync and asynchronous writeAsync.


about news main