Promises in JavaScript

Promises in JavaScript

Index

What is a Promise? (Promise क्या है?)

Promises JavaScript में asynchronous operations को handle करने का एक तरीका है। Promises का उपयोग तब किया जाता है जब कोई task asynchronous तरीके से complete होता है और हमें उसके successful completion या failure का इंतजार करना पड़ता है। यह हमें callbacks के बजाय एक structured और readable code लिखने में मदद करता है।

Syntax of a Promise (Promise का Syntax)

let myPromise = new Promise(function(resolve, reject) {
    // Asynchronous code here
    let success = true;

    if (success) {
        resolve("Task completed successfully!");
    } else {
        reject("Task failed!");
    }
});

resolve(): यह function तब call किया जाता है जब task successfully complete होता है।

reject(): यह function तब call किया जाता है जब task fail हो जाता है।

Using a Promise (Promise का उपयोग)

Promises को handle करने के लिए हम .then() और .catch() methods का उपयोग करते हैं।

  • .then(): यह method तब execute होता है जब promise fulfilled (success) होता है।
  • .catch(): यह method तब execute होता है जब promise rejected (fail) होता है।

Example: Basic Promise

let myPromise = new Promise(function(resolve, reject) {
    let taskCompleted = true;

    if (taskCompleted) {
        resolve("The task was successful.");
    } else {
        reject("The task failed.");
    }
});

myPromise.then(function(result) {
    console.log(result); // Output: The task was successful.
}).catch(function(error) {
    console.log(error);  // If rejected: Output: The task failed.
});


No comments:

Post a Comment

Most recent Post

Promises in JavaScript

Promises in JavaScript Index What is a Promise? (Promise क्या है?) Syntax of a Promise (Promise का Syntax) Using a Promise...