Discover Promises in Bnlang
A Promise in Bnlang represents a value that may be available now, later, or never.
It is a structured way to handle asynchronous operations without falling into callback nesting.
A promise has three states: pending, fulfilled, and rejected.
Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
myPromise.then((msg) => console.log(msg))
.catch((err) => console.error(err));
Chaining Promises
Promises can be chained using .then()
to handle sequences of asynchronous tasks.
new Promise((resolve) => resolve(2))
.then((n) => n * 2)
.then((n) => n * 3)
.then((result) => console.log(result)); // 12
Promise.all
Promise.all
runs multiple promises in parallel and resolves when all are fulfilled.
If any fail, the whole promise rejects.
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]).then((values) => console.log(values)); // [1,2,3]
Best Practices
- Always handle errors with
.catch()
to avoid unhandled rejections. - Use
Promise.all
orPromise.race
for running tasks together. - Keep promises short and focused for readability.