function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
Functions running in parallel with other functions are called asynchronous
When using the JavaScript function setTimeout(), you can specify a callback function to be executed on time-out
Click on below button (It will show output after 3 seconds)
setTimeout(show, 3000)
function show()
{
document.getElementById("showMsg").innerHTML = "Javascript is most popular language..!";
}
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
//Promise 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 */ }
);
//Example
function myDisplayer(some) {
document.getElementById("demo").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);}
);
async and await make promises easier to write
The keyword async before a function makes the function return a promise
The keyword await before a function makes the function wait for a promise
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("Revolution");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
We will fetch text from text document on button click
<input type="button" value="Read Text" onclick="getText('fetchapiex.txt');" >
<p id="fetch"></p >
<script>
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
document.getElementById("fetch").innerHTML = y;
}
</script>