Synchronous:
- In synchronous operations tasks are performed one at a time and only when one
is completed, the following is unblocked. In other words, you need to wait for a
task to finish to move to the next one.
Asynchronous:
- In asynchronous operations, you can move to another task
before the previous one finishes.
Synchronous Execution
My boss is a busy man. He tells me to write code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?"
he's like: "No, I'm waiting right here until you finish." This is synchronous.
Asynchronous Execution
The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution.
(Take my advice: NEVER work with the boss behind you.)
Synchronous: In synchronous operations tasks are performed one at a time and only when one
is completed, the following is unblocked. In other words, you need to wait for a
task to finish to move to the next one.
function getUsername(callback) {
setTimeout(() => {
console.log("Alextz")
callback()
}, 2000)
}
getUsername(() => console.log("getUsername callback called"))
Asynchronous: In asynchronous operations, you can move to another task
before the previous one finishes.
function getUser(callback) {
setTimeout(() => {
console.log("Alextz")
}, 2000)
// get executed even though the user has not printed yet
callback()
}
getUser(() => console.log("getUser callback called"))
// synchronous - Means execute the next one even though the previous
// has not finished yet
// asynchronous - Means wait for the previous operation to finish and then execute
// the next one
// sync example
function getUser(callback) {
setTimeout(() => {
console.log("Alextz")
}, 2000)
// get executed even though the user has not printed yet
callback()
}
getUser(() => console.log("getUser callback called"))
// asynchronous example
// the callback must wait for the username to be displayed 1st
function getUsername(callback) {
setTimeout(() => {
console.log("Alextz")
callback()
}, 2000)
}
getUsername(() => console.log("getUsername callback called"))
function f1() {
// some code
}
function f2() {
// some code
}
function f3() {
// some code
}
// Invoke the functions one by one
f1();
f2();
f3();