Today you will learn:
setTimeout for delayed executionasync/await syntax for cleaner async codeBy the end, you will be able to manage time-dependent operations and API calls in JavaScript.
Run code after a delay:
setTimeout(() => {
console.log("This prints after 2 seconds");
}, 2000);
Promises represent a value that may be available now or in the future:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 2000);
});
promise.then(console.log); // "Data loaded" after 2s
Simpler syntax to handle promises:
async function getData() {
return "Data loaded";
}
getData().then(console.log); // "Data loaded"
async function getData() {
return "Data loaded";
}
getData().then(console.log);
Create a promise that resolves after 2 seconds:
const waitTwoSeconds = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolved after 2 seconds"), 2000);
});
waitTwoSeconds.then(console.log);