- JavaScript Introduction
- JavaScript Where To
- JavaScript Output
- JavaScript Statements
- JavaScript Syntax
- JavaScript Comments
- JavaScript Variables
- JavaScript Let
- JavaScript Const
- JavaScript Operators
- JavaScript Assignment
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Const
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Random
- JavaScript Booleans
- JavaScript Comparison And Logical Operators
- JavaScript If Else And Else If
- JavaScript Switch Statement
- JavaScript For Loop
- JavaScript Break And Continue
- JavaScript Type Conversion
- JavaScript Bitwise Operations
- JavaScript Regular Expressions
- JavaScript Errors
- JavaScript Scope
- JavaScript Hoisting
- JavaScript Use Strict
- The JavaScript This Keyword
- JavaScript Arrow Function
- JavaScript Classes
- JavaScript JSON
- JavaScript Debugging
- JavaScript Style Guide
- JavaScript Common Mistakes
- JavaScript Performance
- JavaScript Reserved Words
- JavaScript Versions
- JavaScript History
- JavaScript Forms
- JavaScript Validation API
- JavaScript Objects
- JavaScript Object Properties
- JavaScript Function Definitions
- JavaScript Function Parameters
- JavaScript Function Invocation
- JavaScript Closures
- JavaScript Classes
- Java Script Async
- JavaScript HTML DOM
- The Browser Object Model
- JS Ajax
- JavaScript JSON
- JavaScript Web APIs
- JS Vs JQuery
Java Script Async
JavaScript Callbacks
"I will call back later!"
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.
This example will end up displaying "Goodbye":
Example
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
This example will end up displaying "Hello":
Example
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
mySecond();
myFirst();
Sequence Control
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation, and then display the result.
You could call a calculator function (myCalculator
), save the result, and then call another function (myDisplayer
) to display the result:
Example
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}
let result = myCalculator(5, 5);
myDisplayer(result);
Or, you could call a calculator function (myCalculator
), and let the calculator function call the display function (myDisplayer
):
Example
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
The problem with the first example above, is that you have to call two functions to display the result.
The problem with the second example, is that you cannot prevent the calculator function from displaying the result.
Now it is time to bring in a callback.
JavaScript Callbacks
A callback is a function passed as an argument to another function.
Using a callback, you could call the calculator function (myCalculator
) with a callback, and let the calculator function run the callback after the calculation is finished:
Example
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
In the example above, myDisplayer
is the name of a function.
It is passed to myCalculator()
as an argument.
When you pass a function as an argument, remember not to use parenthesis.
Right: myCalculator(5, 5, myDisplayer);
Wrong: myCalculator(5, 5, myDisplayer());
When to Use a Callback?
The examples above are not very exciting.
They are simplified to teach you the callback syntax.
Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).
Practice Excercise Practice now
Asynchronous JavaScript
"I will finish later!"
Functions running in parallel with other functions are called asynchronous
A good example is JavaScript setTimeout()
Asynchronous JavaScript
The examples used in the previous chapter, was very simplified.
The purpose of the examples was to demonstrate the syntax of callback functions:
Example
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
In the example above, myDisplayer
is the name of a function.
It is passed to myCalculator()
as an argument.
In the real world, callbacks are most often used with asynchronous functions.
A typical example is JavaScript setTimeout()
.
Waiting for a Timeout
When using the JavaScript function setTimeout()
, you can specify a callback function to be executed on time-out:
Example
function myFunction() {
document.getElementById("demo").innerHTML = "I love You !!";
}
In the example above, myFunction
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 myFunction()
will be called after 3 seconds.
When you pass a function as an argument, remember not to use parenthesis.
Right: setTimeout(myFunction, 3000);
Wrong: setTimeout(myFunction(), 3000);
Instead of passing the name of a function as an argument to another function, you can always pass a whole function instead:
Example
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
In the example above, function(){ myFunction("I love You !!!"); }
is used as a callback. It is a complete function. The complete function is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction()
will be called after 3 seconds.
Waiting for Intervals:
When using the JavaScript function setInterval()
, you can specify a callback function to be executed for each interval:
Example
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
In the example above, myFunction
is used as a callback.
The function (the function name) is passed to setInterval()
as an argument.
1000 is the number of milliseconds between intervals, so myFunction()
will be called every second.
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.
This example loads a HTML file (mycar.html
), and displays the HTML file in a web page, after the file is fully loaded:
Waiting for a File:
document.getElementById("demo").innerHTML = some;
}
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(this.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
In the example above, myDisplayer
is used as a callback.
The function (the function name) is passed to getFile()
as an argument.
Below is a copy of mycar.html
:
<img src="img_car.jpg" alt="Nice car" style="width:100%">
<p>A car is a wheeled, self-powered motor vehicle used for transportation.
Most definitions of the term specify that cars are designed to run primarily on roads, to have seating for one to eight people, to typically have four wheels.</p>
<p>(Wikipedia)</p>
Practice Excercise Practice now
JavaScript Promises
"I Promise a Result!"
"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
JavaScript Promise Object
A JavaScript Promise object contains both the producing code and calls to the consuming code:
Promise Syntax
// "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 */ }
);
When the executing code obtains the result, it should call one of the two callbacks:
Result | Call |
---|---|
Success | myResolve(result value) |
Error | myReject(error object) |
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.
myPromise.state | myPromise.result |
---|---|
"pending" | undefined |
"fulfilled" | a result value |
"rejected" | an error object |
You cannot access the Promise properties state and result.
You must use a Promise method to handle promises.
Promise How To
Here is how to use a Promise:
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.
Example
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// The producing code (this may take some time)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
JavaScript Promise Examples
To demonstrate the use of promises, we will use the callback examples from the previous chapter:
- Waiting for a Timeout
- Waiting for a File
Waiting for a Timeout
Example Using Callback
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
Example Using Promise
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Waiting for a file
Example using Callback
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(req.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
Example using Promise
let req = new XMLHttpRequest();
req.open('GET', "mycar.htm");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Practice Excercise Practice now
JavaScript Async
"async and await make promises easier to write"
async makes a function return a Promise
await makes a function wait for a Promise
Async Syntax
The keyword async
before a function makes the function return a promise:
Example
return "Hello";
}
return Promise.resolve("Hello");
}
Here is how to use the Promise:
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Example
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Or simpler, since you expect a normal value (a normal response, not an error):
Example
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);}
);
Await Syntax
The keyword await
before a function makes the function wait for a promise:
The await
keyword can only be used inside an async
function.
Example
Let's go slowly and learn how to use it.
Basic Syntax
let myPromise = new Promise(function(myResolve, myReject) {
myResolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
Waiting for a Timeout
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
Waiting for a File
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {myResolve(req.response);}
else {myResolve("File not Found");}
};
req.send();
});
document.getElementById("demo").innerHTML = await myPromise;
}
getFile();
Browser Support
ECMAScript 2017 introduced the JavaScript keywords async
and await
.
The following table defines the first browser version with full support for both:
Chrome 55 | Edge 15 | Firefox 52 | Safari 11 | Opera 42 |
Dec, 2016 | Apr, 2017 | Mar, 2017 | Sep, 2017 | Dec, 2016 |
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP