asynchronous and synchronous javascript code example
Example 1: js use await in synchronous method
var btn = document.getElementById("btn");
btn.addEventListener("click", handler, false);
function handler(e) {
console.log("handler triggered");
doSomething();
console.log("handler done");
}
function doSomething() {
doThis();
doThat();
doTheOther();
}
function doThis() {
console.log("doThis - start & end");
}
function doThat() {
console.log("doThat - start");
var stop = Date.now() + 1000;
while (Date.now() < stop) {
}
console.log("doThat - end");
}
function doTheOther() {
console.log("doThat - start & end");
}
Example 2: synchronous vs asynchronous functions javascript
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");