JavaScript Promise at a Glance
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 ফাংশনটি ডেটাকে পার্স করে এবং ১ সেকেন্ড পর তা রিটার্ন করে।
- ডেটা ডিসপ্লে করা: সবশেষে, প্রসেস করা ডেটা কনসোলে দেখানো হয়। 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.
