What is the point of callbacks? take this asynchronous code for example:
console.log("Start");
function loginUser(email, password) {
setTimeout(() => {
console.log("now we have the data")
console.log({userEmail: email})
getUserVideos()
}, 3000);
}
function getUserVideos() {
setTimeout(() => {
console.log("now we have the videos")
console.log(["video1", "video2", "video3"])
}, 7000)
}
const user = loginUser("dhbd@goomail.com", 123456)
console.log("Finish");
And here’s another version of the code using callbacks:
console.log("Start");
function loginUser(email, password, callback) {
setTimeout(() => {
console.log("now we have the data")
callback({userEmail: email})
}, 3000);
}
function getUserVideos(callback) {
setTimeout(() => {
console.log("now we have the videos")
callback(["video1", "video2", "video3"])
}, 7000)
}
const user = loginUser("dhbd@goomail.com", 123456, (user) => {
console.log(user)
getUserVideos((videos) => {
console.log(videos)
})
})
console.log("Finish");
I cannot see any difference in the output of the two! can you then explain why we use callbacks?
Do they have something to do with customer-server communication or something like that?