// Callback hell ๐ฅ
timer(1000, function () {
console.log("work");
timer(1000, function () {
console.log("work");
timer(1000, function () {
console.log("work");
});
});
});
// Promise heaven
timer(1000)
.then(function () {
console.log("work");
return timer(1000);
})
.then(function () {
console.log("work");
return timer(1000);
})
.then(function () {
console.log("work");
return timer(1000);
});
// Async and await
// ๋ฌธ๋ฒ์ ๋จ์ํจ, ๋๊ธฐ์ ์ผ๋ก ๋ณด์ด๊ธธ ์ํจ
// ๋น๋๊ธฐ์ ์ธ ํจ์ ์์ await๋ฅผ ๋ถ์ธ๋ค.
// async ์์ ๋ค์ด์์ด์ผ ํ๋ค.
async function run() {
await timer(1000);
console.log("work");
await timer(1000);
console.log("work");
await timer(1000);
console.log("work");
}
run();
A function which is to be executed after another function has finished execution.
JavaScript execute the code block by order after *hoisting.
*hoisting var, function declaration.
console.log("1");
setTimeout(() => console.log("2"), 1000);
console.log("3");
function printImmediately(tomato) {
tomato();
// This fuction takes a callback as a parameter named "tomato"
}
printImmediately(() => console.log("hello"));
// A function that takes a callback as a parameter and processes it.
====================================================================
// Same thing
printImmediately(() => console.log("hello"));
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log("async callback"), 2000);
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if ((id === "ellie" && password === "dream") ||
(id === "coder" && password === "academy"))
{
onSuccess(id);
} else {
let err = new Error("not found");
// โญ
// == onError(new Error("no access"));
onError(err);
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === "ellie") {
onSuccess({ name: "ellie", role: "admin" });
} else {
onError(new Error("no access"));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage.loginUser(
id,
password,
(user) => {
userStorage.getRoles(
user,
(onSuccess) => {
alert(`Hello ${onSuccess.name}, you have a ${onSuccess.role} role`);
},
(error) => {
console.log(error);
}
);
},
(error) => {
console.log(error);
}
);
Promise is a JavaScript object for asynchronous operation. It can be used as alternatives to callback functions.
In JavaScript, a Promise can exist in one of three states: "pending," "fulfilled," or "rejected.โ