JavaScript: JavaScript Async Programming

🗓 Last updated: 2026-11-30👤 Written by: Alex✓ Reviewed by: Dana🏷 Category: JavaScript Tutorial

JavaScript is single-threaded — it can only do one thing at a time. But if a network request takes 3 seconds, should the page freeze for 3 seconds? Of course not. Async programming solves this: instead of waiting around, you take a number and come back when it's ready. Like a restaurant queue system — you don't stand at the kitchen door, you sit down and wait for your number to be called.


Related Async Methods:async/await Promise.allSettled Promise.race Promise.all setTimeout Promise catch then

1. Sync vs Async

Synchronous: Code executes line by line — the next line waits for the current one to finish. Like standing in line — you wait until the person ahead of you is done.

Asynchronous: Certain operations (network requests, timers, file I/O) start without blocking subsequent code. When they finish, you're notified via a callback or Promise.

HTML
<!-- Script tag -->
<script>
console.log('1');
setTimeout(function() {
  console.log('2');
}, 1000);
console.log('3');
</script>

The output order is 1 → 3 → 2. setTimeout is asynchronous — its callback runs after 1 second without blocking console.log('3').



2. Callbacks

Callbacks are the most basic async pattern — pass a function as an argument, and it gets called when the async operation completes.

▶ Example: Basic Callback Usage

▶ Try it Yourself

(1) Callback Hell

When async operations depend on each other in sequence, callbacks nest deeper and deeper — this is the infamous "Callback Hell."

HTML
<!-- Script tag -->
<script>
getUser(function(user) {
  getOrders(user.id, function(orders) {
    getOrderDetail(orders[0].id, function(detail) {
      getItems(detail.itemId, function(items) {
        console.log('4 levels deep — add more complexity and it becomes unreadable');
      });
    });
  });
});
</script>
💡 Tip: Callback hell looks like a "horizontal pyramid" — hard to read and maintain. Promises were invented to solve this.



3. Promise

A Promise is an object that represents the eventual result of an async operation. It has three states:

State Description
pending In progress, no result yet
fulfilled Completed successfully, result available
rejected Failed, error available

Once a Promise transitions from pending to fulfilled or rejected, it never changes back — like an arrow once shot, it can't be recalled.

(1) Creating a Promise

HTML
<!-- Script tag -->
<script>
const promise = new Promise(function(resolve, reject) {
  // async operation
  // call resolve(result) on success
  // call reject(error) on failure
});
</script>

(2) then / catch / finally

HTML
<!-- Script tag -->
<script>
promise
  .then(function(result) { console.log(result); })   // runs on success
  .catch(function(error) { console.error(error); })    // runs on failure
  .finally(function() { console.log('Done'); });       // runs regardless
</script>

▶ Example: Simulating a Request with Promise

▶ Try it Yourself

(3) Chaining

then itself returns a Promise, so you can chain calls — callback hell becomes a straight line.

HTML
<!-- Script tag -->
<script>
fetchUser()
  .then(function(user) { return fetchOrders(user.id); })
  .then(function(orders) { return fetchDetail(orders[0].id); })
  .then(function(detail) { console.log(detail); })
  .catch(function(err) { console.error(err); });
</script>
💡 Tip: A single catch at the end of the chain catches errors from any step — you don't need a catch after every then.



4. async / await

async/await is syntactic sugar over Promises — it makes async code look synchronous, greatly improving readability.

▶ Example: Rewriting the Above Request with async/await

▶ Try it Yourself
💡 Tip: Compared to callbacks, async/await turns "take a number and wait" into "stay in line without leaving" — the code flow is straight and readability skyrockets.

(1) Error Handling

async/await uses try/catch for error handling — the same pattern used with synchronous code.

HTML
<!-- Script tag -->
<script>
async function loadAll() {
  try {
    const user = await fetchUser();
    const orders = await fetchOrders(user.id);
    console.log(orders);
  } catch (err) {
    console.error('Something went wrong:', err);
  }
}
</script>


5. Promise.all and Promise.race

Method Description
Promise.all([p1, p2, p3]) Succeeds only if all succeed; fails as soon as one fails
Promise.race([p1, p2, p3]) Uses the result of whichever settles first (success or failure)

▶ Example: Concurrent Requests with Promise.all

▶ Try it Yourself
💡 Tip: Promise.all is like a group dinner — everyone must arrive before you eat. Promise.race is like a race — whoever finishes first wins. Use all for independent requests to speed things up, and race when you have multiple mirror sources and want the fastest one.


Related Async Methods:async/await Promise.allSettled Promise.race Promise.all setTimeout Promise catch then

❓ FAQ

Q What exactly is the difference between synchronous and asynchronous in JavaScript?
A Synchronous code runs in order, so the next line won't execute until the previous one finishes; asynchronous code returns immediately after being started, and the result is obtained later via a callback, Promise, or await. For example, setTimeout doesn't block subsequent code, whereas a time-consuming loop will stall the entire main thread.
Q Why does writing await inside a regular function throw an error?
A await can only be used inside an async function, and using it in a regular function throws a syntax error directly. The fix is to declare that function as async, or switch to handling the Promise with .then(); at the top level of a module you can use await directly, but be mindful of whether the runtime supports it.
Q How should I choose between Promise.all and Promise.race?
A Use Promise.all when you need all tasks to succeed, since any single failure rejects the whole thing; use Promise.race when you only care about whichever settles first (success or failure), which is commonly used for timeout control. If you want to wait for everything to finish without being interrupted by failures, use Promise.allSettled.

📖 Summary

📝 Exercises

  1. Basic: Use Promise + setTimeout to simulate a 2-second delay, then output "Done" on success.
  2. Intermediate: Rewrite the above with async/await and add try/catch error handling.
  3. Challenge: Use Promise.all to fire 3 simulated requests with different delays (1s/2s/3s) concurrently, then calculate and display the total elapsed time when all complete.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏