JavaScript - tutorial - 27 - asynchronous

revision:


Content

JavaScript callbacks asynchronous JavaScript JavaScript promises JavaScript async


JavaScript callbacks

top

a callback is a function passed as an argument to another function

this technique allows a function to call another function. A callback function can run after another function has finished

function sequence

JavaScript functions are executed in the sequence they are called, not in the sequence they are defined.

examples

code:
                    <div class="spec">
                        <a id="demo"></a><br>        
                    </div>
                    <script>
                        function myDisplayer(some) {
                            document.getElementById("demo").innerHTML += some + ", ";
                        }
                        function myFirst() {
                            myDisplayer("Hello");
                        }
                        function mySecond() {
                            myDisplayer("Goodbye");
                        }
                        mySecond();
                        myFirst();
                    </script>
                
code:
                        function myDisplay(some) {
                            document.getElementById("demo1").innerHTML += some;
                        }
                        function myFirst() {
                            myDisplay("Hello");
                        }
                        function mySecond() {
                            myDisplay("Goodbye");
                        }
                        myFirst();
                        mySecond();
                    

sequence control solutions:

1/ You could call a function, save the result, and then call another function to display the result.

problem : you have to call two functions to display the result.

2/ You could call a function and let this function call the other function to display the result.

problem : you cannot prevent the first function from displaying the result.

3/ the callback function : a callback is a function passed as an argument to another function. Using a callback, you could call the function with a callback, and let the function run the callback after the result is obtained.

examples

do a calculation and then display the result

code
                    <div class="spec">
                        <a id="demo2"></a>         
                    </div>
                    <script>
                        function myDisplayer(some) {
                            document.getElementById("demo2").innerHTML = some;
                        }
                        function myCalculator(num1, num2, myCallback) {
                            let sum = num1 + num2;
                            myCallback(sum);
                        }
                        myCalculator(5, 5, myDisplayer);
                    </script>
                

NOTE: when you pass a function as an argument, remember not to use parenthesis :

correct/right : myCalculator(5, 5, myDisplayer);
wrong : myCalculator(5, 5, myDisplayer());

when to use a callback?

Where callbacks really shine are in asynchronous functions, i.e. where one function has to wait for another function (like waiting for a file to load).


asynchronous JavaScript

top

asynchronous functions: functions running in parallel with other functions

waiting for a timeout: when using the JavaScript function setTimeout(), you specify a callback function to be executed on time-out.

examples

wait 3 seconds (3000 milliseconds) for this page to change.

refresh page!!

code:
                    <div class="spec">
                        <p>refresh page!!</p>  
                        <a id="demo3"></a>      
                    </div>
                    <script>
                        function setT() {
                            document.getElementById("demo3").innerHTML = "How do you do?!!";
                        }
                        setTimeout(setT, 3000);
                    </script>
                

explanation: setT is used as a callback. The function (the function name) is passed to setTimeout() as an argument. 3000 is the number of milliseconds before time-out, so setT() will be called after 3 seconds.

Instead of passing the name of a function as an argument to another function, you can always pass a whole function instead.

examples

wait 4 seconds (4000 milliseconds) for this page to change.

refresh page!!

code:
                    <div>
                    <p>refresh page!!</p>  
                        <a id="demo4"></a>        
                    </div>
                    <script>
                        setTimeout (function() { myFun("Good to hear from you!!");}, 4000);
                        function myFun(value) {
                            document.getElementById("demo4").innerHTML = value;
                        }
                    </script>
                

explanation: function(){ myFun("Good to hear from you !!!"); } is used as a callback. It is a complete function, which is passed to setTimeout() as an argument. 4000 is the number of milliseconds before time-out, so myFun() will be called after 4 seconds.

waiting for intervals: when using setInterval(), a callback function can be specified to be executed for each interval

examples

using setInterval() to display the time every second (1000 milliseconds).

code:
                    <div class="spec">
                        <a id="demo5"></a>        
                    </div>
                    <script>
                        setInterval(showTime, 1000);
                        function showTime() {
                            let d = new Date();
                            document.getElementById("demo5").innerHTML = d.getHours() + ":" 
                            + d.getMinutes() + ":" + d.getSeconds();
                        }
                    </script>
                

waiting for files

if you create a function to load an external resource (like a script or a file), you cannot use the content before it is fully loaded. This is the perfect time to use a callback.


JavaScript promises

top

Promise object

a JavaScript Promise object contains both the producing code and calls to the consuming code. "Producing code" is code that can take some time. "Consuming code" is code that must wait for the result. A promise is a JavaScript object that links producing code and consuming code.

Syntax:

        let myPromise = new Promise(function(myResolve, myReject) {
            // "Producing Code" (May take some time)
                myResolve(); // when successful
                myReject();  // when error
                });
            // "Consuming Code" (Must wait for a fulfilled Promise)
                myPromise.then(
                function(value) { /* code if successful */ },
                function(error) { /* code if some error */ }
                );
    

Promise object properties

a JavaScript Promise object can be: pending, fulfilled, rejected. The Promise object supports two properties: state and result. While a Promise object is "pending" (working), the result is undefined. When a Promise object is "fulfilled", the result is a value. When a Promise object is "rejected", the result is an error object.

You cannot access the Promise properties state and result. You must use a Promise method to handle promises. Here is how to use a Promise:

        myPromise.then(
        function(value) { /* code if successful */ },
        function(error) { /* code if some error */ }
      );
    

Promise.then() takes two arguments, a callback for success and another for failure.Both are optional, so you can add a callback for success or failure only.

examples

JavaScript Promise

code:
                    <div class="spec">
                        <a id="demo6"></a>    
                    </div>
                    <script>
                        function myDisplayer(some) {
                            document.getElementById("demo6").innerHTML = some;
                        }
            
                        let myPromise = new Promise(function(myResolve, myReject) {
                        let x = 0;
                        // some code (try to change x to 5)
                        if (x == 0) {
                            myResolve("OK");
                        } else {
                            myReject("Error");
                        }
                        });
                        
                        myPromise.then(
                        function(value) {myDisplayer(value);},
                        function(error) {myDisplayer(error);}
                        );
                    </script>
                

JavaScript Promise - waiting for a Timeout.

wait 3 seconds (3000 milliseconds) for this page to change.

refreshh page!!

code:
                    <div class="spec">
                        <p>refreshh page!!</p>
                        <a id="demo7"></a>        
                    </div>
                    <script>
                        let myPromise1 = new Promise(function(myResolve, myReject) {
                        setTimeout(function(){ myResolve("Iit ends up quite wellc!!"); }, 3000);
                        });
                        
                        myPromise1.then(function(value) {
                        document.getElementById("demo7").innerHTML = value;
                        });
                    </script>
                

JavaScript async

top

"async" makes a function return a Promise.

"await" makes a function wait for a Promise. The keyword "async" before a function makes the function return a promise

examples

JavaScript async. Look at the syntax carefully

code:
                    <div class="spec">
                        <a style="margin-left: 3vw;" id="demo8"></a>
                    </div>
                    <script>
                        function myDisplayer(some) {
                            document.getElementById("demo8").innerHTML = some;
                        }
                        async function myFunction() {return "Hello";}
                        myFunction().then(
                        function(value) {myDisplayer(value);},
                        function(error) {myDisplayer(error);}
                        );
                    </script>
                

The keyword "await" before a function makes the function wait for a promise: let value = await promise;.
The await keyword can only be used inside an async function.

examples

basic syntax

code:
                    <div class="spec">
                        <a id="demo9"></a>    
                    </div>
                    <script>
                        async function myDisplay() {
                            let myPromise2 = new Promise(function(myResolve, myReject) {
                                myResolve("I love You !!");
                            });
                            document.getElementById("demo9").innerHTML = await myPromise;
                        }
                        myDisplay();
                    </script>
                

waiting for a Timeout

code:
                    <div>
                        <a id="demo10"></a>        
                    </div>
                    <script>
                        async function myDisplay() {
                        let myPromise3 = new Promise(function(myResolve, myReject) {
                            setTimeout(function() { myResolve("I love You !!"); }, 3000);    
                        });
                        document.getElementById("demo10").innerHTML = await myPromise3;
                        }
                        myDisplay();
                    </script>