What is Asynchrony?
JavaScript runs on a single thread. Asynchronous code lets you start tasks that may take time (like network requests) without blocking the rest of your program.
Callbacks
Old‑style async uses functions passed as arguments.
function fetchData(callback){
setTimeout(()=>{ callback('Data loaded'); },1500);
}
fetchData(result=> console.log(result)); // "Data loaded" after 1.5s
Promises
Promises provide a cleaner way to handle async results.
function fetchData(){
return new Promise(resolve=>{
setTimeout(()=>resolve('Data loaded'),1500);
});
}
fetchData().then(result=> console.log(result));
Async / Await
Async functions let you write asynchronous code that looks synchronous.
async function getData(){
const result = await fetchData(); // returns a Promise
console.log(result);
}
Fetch API Example
Fetch data from a public API and display it.
Try It Yourself
Edit the code below and click Run. The output will appear below.