Home  >  Article  >  Web Front-end  >  Javascript Promis

Javascript Promis

王林
王林Original
2024-07-18 10:37:15957browse

Image description

JavaScript promises are one of the convenient ways to manage asynchronous operations. promises represent values ​​that may be fulfilled or fail in the future. They are used to manage the results of asynchronous operations and reduce problems with callback functions.

promises table

Image description

Create

promises

The Promise constructor is used to create a promise in JavaScript.

let myPromise = new Promise((resolve, reject) => {
    let success = true; // Bu yerda sizning asinxron operatsiyangiz bo'lishi mumkin

    if (success) {
        resolve("Bu operatsiya muvaffaqiyatli tugadi!");
    } else {
        reject("Bu operatsiya muvaffaqiyatsiz tugadi.");
    }
});

  • resolve
  • reaject
The

resolve and reject functions are used to control the result of JavaScript promises asynchronous operations.

resolve

The

resolve function is called when the promise is successfully executed. This function takes a value as an argument, and this value is then passed to the .then() method.

let Promise = new Promise((resolve, reject) => {
    let success = true; // Bu yerda sizning asinxron operatsiyangiz bo'lishi mumkin

    if (success) {
        resolve("Bu operatsiya muvaffaqiyatli tugadi!");
    }
});

In the above example, if the success variable is true, the resolve function is called and "This operation completed successfully!" transmits the value.

Output the result in cansole.log via the

then method:

Promise.then((result) => {
    console.log(result); // "Bu operatsiya muvaffaqiyatli tugadi!" ni cansole.log da chiqaradi
});

reject

The

reject function is called when the promise fails. This function takes as an argument information about an error or failure, and this value is then passed to the .catch() method.

let mPromise = new Promise((resolve, reject) => {
    let success = false; // Bu yerda sizning asinxron operatsiyangiz bo'lishi mumkin

    if (!success) {
        reject("Bu operatsiya muvaffaqiyatsiz tugadi.");
    }
});

In the example above, if the success variable is false, the reject function is called and "This operation failed." transmits the value.

mPromise
    .then((result) => {
        console.log(result); // Bu yerga kirmaydi keyingi blockga o'tadi
    })
    .catch((error) => {
        console.error(error); // "Bu operatsiya muvaffaqiyatsiz tugadi." ni cansole.logda chop  etadi
    });

Image description

The above is the detailed content of Javascript Promis. 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