search
HomeWeb Front-endJS TutorialJavaScript Promise at a Glance

এক নজরে জাভাস্ক্রিপ্ট Promise

La promesse en JavaScript fonctionne comme un conteneur de valeur future. Par exemple, promise peut être utilisé lorsque vous n’avez pas besoin d’une valeur maintenant mais que vous en aurez besoin plus tard dans le futur. Encore une fois, la promesse agit comme un proxy pour l'achèvement final ou l'échec de l'opération asynchrone. Supposons que vous récupériez des données d'un serveur via une opération asynchrone dans votre code, la promesse peut également être utilisée dans de telles situations.

Règles pour faire des promesses

new Promise est une fonction constructeur de js es6 que nous utilisons pour créer un objet de promesse. Pour créer cette fonction ou ce constructeur, nous devons donner une fonction de rappel comme argument et il y a deux autres paramètres à l'intérieur de cette fonction de rappel, l'un est reslove et l'autre est rejet. Ici, la résolution et le rejet sont deux fonctions

.

let p1 = new Promise((resolve,reject)=>{})

Dans ce cas, si p1 est console.log(p1), alors nous pouvons voir en attente. C'est parce que nous n'avons effectué aucun travail dans le cadre de cette promesse et que le rejet de résolution n'a pas eu lieu. Autrement dit, il existe 3 états de promesse, le premier est en attente et résolu ou rejeté. Cela signifie que la promesse termine toujours son travail à travers 3 états. Cela commence généralement par en attente et si solve() est appelé depuis la fonction de rappel à l'intérieur de la promesse, l'état de la promesse sera rempli ou si rejet() est appelé depuis la fonction de rappel, l'état de la promesse sera rejeté. Si l’état de la promesse est rejeté, cela est considéré comme une erreur.

Regardons maintenant l'exemple ci-dessus Arectu :

let p = new Promise((res,rej)=>{
    setTimeout(()=>{
        res("hello world")
    },5000) 
}) 

Maintenant, si nous consolons la variable p dans le navigateur, nous pouvons voir que l'état de la promesse sera en attente et après 5 secondes, si nous consolons p, l'état de la promesse s'affichera terminé.

Parlons maintenant de la façon d'obtenir la valeur du rappel dans la promesse ? Pour cela, nous devons utiliser .then() et .catch(). Eh bien, voyons maintenant comment la valeur de promise est extraite avec la syntaxe .then() et .catch().

//promise declare with new Promise constructor
let p = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve ("hello world")
    },5000) 
}) 

// promise consume 
p.then((v )=>{ 
console.log(v ) // output- hello world
}).catch((error) =>{ 
console.log(error)
}) 

Après 5 secondes dans ce code, je peux voir "hello world". Comment est-ce arrivé? Notez que nous venons d'appeler la fonction solve() depuis la fonction setTimeout dans le constructeur de promesse qui s'exécutera après 5 secondes.

এবার .then() এবং .catch() মেথড নিয়ে আরেক্টু আলোচনা করা যাক।

1. Promise then() মেথড

promise এর method তখন এ invoked করা যাবে যখন promise এর স্টেট fulfiled অথবা rejected হবে তখন । .then() মেথড প্যারামিটার হিসেবে ২টি ফাংশন নেয় । ১ম ফাংশনটি এক্সিকিউট হবে যদি promise এর স্টেট fulfiled হয় এবং ২য় ফাংশনটি এক্সিকিউট হবে যদি promise এর স্টেট rejected হয় ( যদিও ২য় ফাংশনটি অপশনাল তবে আমরা promise যদি rejected হয় সেই ক্ষেত্রে .catch() মেথড ব্যবহার করতে পারি )। resolve এবং rejected এর value রিসিভ করার জন্য প্রত্যেকটা ফাংশনে একটা করে প্যারামিটার রিসিভ করে । চলেন এক্সাম্পল দেখি তাইলে আরেক্টু বুঝতে পারবেন।

Example - 1

//promise declare with new Promise constructor
let promise = new Promise(function (resolve, reject) {
      resolve('Hello world '); 
})

// promise consume
promise
    .then(function (successMessage) {
        //success handler function is invoked  when promise state will be fulfiled 
        console.log(successMessage);
    }, function (errorMessage) {
        console.log(errorMessage);
    }); 

// output- Hello world

এখানে খেয়াল করুন.then() মেথড এর প্রথম ফাংশনটি এক্সিকিউট হচ্ছে উপরে resolve() ফাংশনটি কল হওয়ার কারণে। এখানে resolve("Hello world ") এইভাবে লিখা হয়েছে অর্থাৎ resolve ফাংশনটি আর্গুমেন্ট সহ কল হচ্ছে। সেই আরগুমেন্টি রিসিভ করার জন্য .then()মেথড এর প্রথম ফাংশনে successMessage নামে একটা প্যারামিটার রিসিভ করে সেই প্যারামিটার এর ভিতরে Hello world লিখাটি পাচ্ছি।

Example - 2

let promise = new Promise(function (resolve, reject) {
    reject('Promise Rejected')
})

promise
    .then(function (successMessage) {
        console.log(successMessage);
    }, function (errorMessage) {
        //error handler function is invoked 
        console.log(errorMessage);
    }); 

// output- Promise Rejected

এখানে খেয়াল করুন .then() মেথড এর দ্বিতীয় ফাংশনটি এক্সিকিউট হচ্ছে উপরে rejected() ফাংশনটি কল হওয়ার কারণে। এখানে rejected ("Promise Rejected ")এইভাবে লিখা হয়েছে অর্থাৎ rejected ফাংশনটি আর্গুমেন্ট সহ কল হচ্ছে। সেই আরগুমেন্টি রিসিভ করার জন্য.then() মেথড এর দ্বিতীয় ফাংশনে errorMessage নামে একটা প্যারামিটার রিসিভ করে সেই প্যারামিটার এর ভিতরে Promise Rejected লিখাটি পাচ্ছি।

2. Promise catch() Method

catch() মেথড তখনই invoked হবে যখন promise এর স্টেট rejected হবে অথবা promise এর ভিতরে যদি কোন error ঘটে তখন । এটি ব্যবহার করা হয় মূলত error handling এর জন্য। .catch() মেথড প্যারামিটার হিসেবে একটি কলব্যাক ফাংশন রিসিভ করে এবং সেই কলব্যাক ফাংশনটি আরও একটি প্যারামিটার রিসিভ করে promise এর ভিতরের error কে রিসিভ করার জন্য।

Example:

let promise = new Promise(function (resolve, reject) {
    reject('Promise Rejected')
})

promise
    .then(function (successMessage) {
        console.log(successMessage);
    })
    .catch(function (errorMessage) {
        //error handler function is invoked 
        console.log(errorMessage);
    }); 

output - Promise Rejected

এখানে error টা catch() মেথড এ ঢুকবে কারণ .then() মেথডে প্যারামিটারে আমরা ১ম ফাংশনটি ব্যবহার করেছি যেহেতু .then() মেথড এর প্যারামিটারে ২য় ফাংশনটি ব্যবহার করেনি এবং এর পরিবর্তীতে catch() মেথড ব্যবহার করেছি তাই promise কন্সট্রাক্টর এর ভিতরে যদি promise এর state rejected হয় অথবা কোন error ঘটে তখন সেটি .catch() মেথড এর প্যারামিটার এর কলব্যাক ফাংশনে চলে আসবে।

Chaining Promises

কখনও কখনও, আপনাকে একের পর এক promise নিয়ে কাজ করা লাগতে পারে । যেমন আপনি কোন একটা সার্ভার থেকে ডাটা নিয়ে আসবেন তারপরে ডাটা চলে আসলে আপনি সেই ডাটা প্রসেস করবেন এবং প্রসেস করা শেষ হলে আপনি সেটি ডিসপ্লে করাবেন। এমন পর পর কাজ যদি করতে হয় তাহলে আপনি promise চেইন ব্যবহার করতে পারেন।
Example:

// fetdchData promise declare with new Promise constructor
const fetchData = () => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res(JSON.stringify({ name: 'Sabbir' }));
    }, 2000);
  });
};

// processData promise declare with new Promise constructor
const processData = data => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res(JSON.parse(data));
    }, 1000);
  });
};

const displayData = (finalData) =>{
  console.log(finalData)
} 


fetchData()
  .then(res => { 
return processData(res)  //processData function invoke with fetch data
})
  .then( data => { 
displayData(data )  //display function invoke with displayData func result
})
  .catch(error => { 
console.log(error) 
}); 

output - {name:"sabbir"}

১। ডেটা ফেচ করা: প্রথমে ডেটা ফেচ করতে হবে, যেটা একটি প্রমিজের মাধ্যমে করা হচ্ছে। এখানে fetchData ফাংশনটি একটি অ্যাসিনক্রোনাস কাজ সিমুলেট করে, যেখানে ২ সেকেন্ড পর একটি JSON অবজেক্ট রিটার্ন হয়।

২ ডেটা প্রসেস করা: ডেটা ফেচ হয়ে গেলে পরবর্তী ধাপ হলো সেই ডেটা প্রসেস করা। এখানে processData ফাংশনটি ডেটাকে পার্স করে এবং ১ সেকেন্ড পর তা রিটার্ন করে।

  1. ডেটা ডিসপ্লে করা: সবশেষে, প্রসেস করা ডেটা কনসোলে দেখানো হয়। displayData ফাংশনের মাধ্যমে এটি করা হয়।

এই ধরনের কাজগুলো যদি ঠিকঠাকভাবে পরপর করতে হয়, তাহলে প্রমিজ চেইনিং ব্যবহার করা লাগে।তবে এখানে একটা catch() ব্যবহার করলে হবে । এখানে যেকোনো promis এ কোন error হলে সেটি এই catch() ব্লক এ চলে আসবে । তো আজ এই পর্যন্তই দেখা হবে আগামীতে ।

The above is the detailed content of JavaScript Promise at a Glance. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools