Asynchronous Programming

Overview


Asynchronous programming was developed to deal with situations where the requested operation involves waiting for a response from another machine or process.

The simplest example occurs when the running code requests data from another machine, as in the following.


$url('https://www.server.com/data.json');
                


The $url function sends a request for data from another server, and then waits for the response.

Waiting for a response from another machine can cause problems and is error prone. For example, what happens if the other machine does not respond. Pausing execution of the processor can cause the user interface to hang.

In these situations, Javascript functions that need to wait for a response will actually not cause the processor to hang, rather, they return an object called a Promise.

The promise object has a function "then", which can be passed a function called a callback. The callback function is called when the response is received. If a callback function is passed as an argument to the then function, it is called and passed the response.


$url('https://www.server.com/data.json').then(function(response){

    //process the response
})
                

This means that when the code makes an asynchronous call such as above, it continues to execute the code following the call, and when the response is received, it is passed to the callback provided.

Async Functions


Functions that are declared using the async keyword can bypass the promise mechanism above. When an asynchronous function is called and has the await keyword in front of the call, the code will stop at the await keyword and wait for the response.


async function(){
    let data = await $url('https://www.server.com/data.json');
}
                

This does not stop the processor. When this code is compiled, it is translated into the promise mechanism described above.

Async Wrapper


A simple way to be able to use the async keyword in a script, is simply to wrap it in a an anoynomous function and the call the function immediately.

The following code demonstrates an async wrapper.


(async ()=>{

let data = await $url('https://www.server.com/data.json');

})();