agyanadda@gmail.com

JS Callbacks and Promises

Asynchronous JavaScript 1 min read Updated Dec 1, 2026 Topic 31 of 38

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>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method handles a rejected Promise?

Exercise 2 True / False

A Promise starts in the pending state.

Exercise 3 Fill in the Blank

Promise.___([p1, p2]) waits for all promises to finish.

Frequently Asked Questions

The browser has one main thread. If JavaScript waited, the whole page would freeze. Async code keeps the page responsive.