JS Asynchronous
On this page
JS Asynchronous
JavaScript runs on a single thread, but it can handle asynchronous operations using callbacks, promises, and async/await.
Async Intro
Asynchronous code allows tasks to run without blocking execution.
console.log("Start");
setTimeout(() => {
console.log("Delayed");
}, 1000);
console.log("End");
Async Timeouts
setTimeout(() => console.log("Runs once"), 1000);
const id = setInterval(() => {
console.log("Repeats");
}, 500);
clearInterval(id);
Async Callbacks
Callbacks were the original async pattern, but can lead to callback hell.
function loadData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
loadData((data) => {
console.log(data);
});
Async Promises
Promises represent a future value.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});
promise
.then((result) => console.log(result))
.catch((err) => console.error(err));
Promise utilities:
Promise.all([Promise.resolve(1), Promise.resolve(2)]) .then((values) => console.log(values));
Async Await
async/await makes asynchronous code look synchronous.
function delay(ms) {
return new Promise((res) => setTimeout(res, ms));
}
async function run() {
await delay(1000);
console.log("Waited 1 second");
}
run();
Async Fetch
Fetch is used to make HTTP requests.
async function load() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await res.json();
console.log(data);
} catch (e) {
console.error("Error:", e);
}
}
load();
Async Debug
Use DevTools Network tab and async stack traces for debugging async code.
async function test() {
debugger;
await Promise.resolve();
}
Async Reference
setTimeout,setInterval- Callback functions
Promise,Promise.all,Promise.raceasync/awaitfetchAPI
Next Step
Continue with JS Modules to structure larger applications.