Some tasks take time — loading data, waiting for a timer. JavaScript does not stop and wait; it continues and handles the result later. This is asynchronous code.
Callbacks
A function passed to another function, to be called when the task finishes:
setTimeout(() => console.log('done'), 1000);
Many nested callbacks become hard to read ("callback hell").
Promises
A Promise is a value that will be ready later. It is pending, then either fulfilled (resolve) or rejected (reject).
loadData()
.then(data => show(data))
.catch(err => showError(err))
.finally(() => hideLoader());
Several at once
Promise.all([p1, p2]) waits for all of them.
Example
Example — Creating and using a Promise
HTML
<button id="go">Check result</button>
<p id="out"></p>
<script>
function getResult(roll) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (roll > 0) resolve({ roll, marks: Math.floor(Math.random() * 100) });
else reject('Invalid roll number');
}, 1000);
});
}
document.getElementById('go').onclick = () => {
const out = document.getElementById('out');
out.textContent = 'Loading...';
getResult(101)
.then(r => out.textContent = `Roll ${r.roll}: ${r.marks} marks`)
.catch(err => out.textContent = 'Error: ' + err)
.finally(() => console.log('Request finished'));
};
</script>