revision:
this technique allows a function to call another function. A callback function can run after another function has finished
JavaScript functions are executed in the sequence they are called, not in the sequence they are defined.
<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>
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.
do a calculation and then display the result
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());
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).
waiting for a timeout: when using the JavaScript function setTimeout(), you specify a callback function to be executed on time-out.
wait 3 seconds (3000 milliseconds) for this page to change.
<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.
wait 4 seconds (4000 milliseconds) for this page to change.
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.
using setInterval() to display the time every second (1000 milliseconds).
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.
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 */ } );
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.
JavaScript Promise
<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.
<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>
"await" makes a function wait for a Promise. The keyword "async" before a function makes the function return a promise
JavaScript async. Look at the syntax carefully
<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.
basic syntax
<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