Asynchronous Flow Control

Asynchronous flow control in Bnlang allows programs to perform non-blocking tasks, such as reading files, making network requests, or handling timers, without stopping the execution of other code.
This ensures efficiency and responsiveness in applications that rely on multiple operations happening together.
Common tools for flow control are callbacks, promises, and async/await.


Callbacks

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded");
  }, 1000);
}

fetchData((result) => {
  console.log(result);
});

Promises

Promises represent values that may be available now, later, or never. They provide a cleaner way to handle asynchronous results than callbacks.

const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Data fetched successfully");
  }, 1000);
});

fetchData.then((data) => {
  console.log(data);
});

Async/Await

async/await makes asynchronous code look synchronous, improving readability and reducing complexity.

async function load() {
  const data = await new Promise((resolve) => {
    setTimeout(() => resolve("Done!"), 1000);
  });
  console.log(data);
}

load();

Best Practices

  • Avoid deeply nested callbacks (callback hell). Prefer promises or async/await.
  • Handle errors with .catch() in promises or try/catch with async/await.
  • Use async flow only when necessary to keep code clean and maintainable.