JavaScript Asynchronous Programming & Callbacks

In Bnlang, asynchronous programming lets your program start tasks (like network requests, file access, or timers) and continue running without waiting.
A callback is a function you pass to another function to be invoked later, typically after an asynchronous operation finishes.
This page explains the callback pattern, error-first callbacks, common pitfalls (callback hell), and safer alternatives.


The Event Loop in One Minute

Bnlang runs an event loop that manages queues of tasks. When an asynchronous operation completes, its callback is queued and executed when the call stack is free. This design keeps programs responsive.


Basic Callback Pattern

function পরে_পড়ো(কলব্যাক) {
  সময়সীমা_নির্ধারণ(() => {
    কলব্যাক(null, "পড়া শেষ!");
  }, 500);
}

পরে_পড়ো((এরর, ডাটা) => {
  যদি (এরর) {
    কনসোল.ত্রুটি("ব্যর্থ:", এরর);
  } নাহলে {
    কনসোল.লগ("ফলাফল:", ডাটা);
  }
});

Error‑First Callbacks

A common convention is error‑first callbacks: the first argument is an error (if any), the second is the result. If err is not null, handle the error and do not use the result.

function কাজ_করো(কলব্যাক) {
  সময়সীমা_নির্ধারণ(() => কলব্যাক(null, 42), 300);
}

কাজ_করো((এরর, মান) => {
  যদি (এরর) ফেরত কনসোল.ত্রুটি(এরর);
  কনসোল.লগ("মান:", মান);
});

Avoiding Callback Hell

  • Break large functions into small, named functions and compose them.
  • Prefer Promises or async/await for sequential flow.
  • Reuse common error handlers.

From Callback to Promise (Promisify)

function কলব্যাক_সহ(a, b, cb) {
  সময়সীমা_নির্ধারণ(() => cb(null, a + b), 200);
}

function প্রতিশ্রুতি_সহ(a, b) {
  ফেরত নতুন প্রতিশ্রুতি((রিজলভ, রিজেক্ট) => {
    কলব্যাক_সহ(a, b, (এরর, যোগফল) => {
      যদি (এরর) রিজেক্ট(এরর);
      নাহলে রিজলভ(যোগফল);
    });
  });
}

প্রতিশ্রুতি_সহ(3, 4).তারপর(কনসোল.লগ); // 7

Mixing Callbacks with Timers

function প্রস্তুত_হওয়া_পর্যন্ত_পোল(isReady, done) {
  const আইডি = ইন্টারভ্যাল(() => {
    যদি (isReady()) {
      ক্লিয়ার_ইন্টারভ্যাল(আইডি);
      done(null, "প্রস্তুত!");
    }
  }, 100);
}

Best Practices Recap

  • Use error‑first callbacks consistently.
  • Keep callback functions pure and small.
  • Prefer promises/async‑await for complex flows.
  • Always clear timers you start.