JavaScriptIntermediate
JavaScript Promise
Promise কী, resolve, reject, then, catch, finally, Promise.all — asynchronous flow নিয়ন্ত্রণের বাংলা গাইড।
11টি অংশবাংলা ভাষায়
Promise হলো একটি async কাজের ভবিষ্যত ফলাফল-এর প্রতিনিধিত্ব — কাজটি এখনো শেষ হয়নি, কিন্তু একদিন হবে (সফল বা ব্যর্থ)।
Promise-এর অবস্থা
pending— চলছেfulfilled(resolved) — সফলrejected— ব্যর্থ
Promise বানানো
const getResult = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
resolve("সফল ডেটা");
} else {
reject("ভুল হয়েছে");
}
}, 1000);
});
getResult
.then((data) => console.log("মিলেছে:", data))
.catch((error) => console.error("সমস্যা:", error))
.finally(() => console.log("শেষ হলো"));then, catch, finally
fetchSomething()
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.warn(error));Promise.all ও Promise.allSettled
const userPromise = loadUser();
const postsPromise = loadPosts();
// সব সম্পন্ন হলে
Promise.all([userPromise, postsPromise])
.then(([user, posts]) => {
console.log(user, posts);
});
// প্রতিটির ফল আলাদাভাবে (ব্যর্থ হলেও)
Promise.allSettled([userPromise, postsPromise])
.then((results) => console.log(results));প্রকৃত ব্যবহার
fetch-এর মতো ব্রাউজার API-গুলো Promise-ভিত্তিক — তাই আপনি নিজে Promise সাধারণত বানাতে হয় না, তবে then/catch/await দিয়ে ব্যবস্থাপনা করতে হয়।
পরবর্তী ধাপ
Promise ব্যবহারের সবচেয়ে পরিষ্কার উপায় হলো async/await — পরের অধ্যায়ে নয়, Fetch API-র সাথে দেখুন।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।