Home > Article > Web Front-end > Javascript Promis
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
Createpromises
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 and reject functions are used to control the result of JavaScript promises asynchronous operations.
resolve
Theresolve 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 thethen method:
Promise.then((result) => { console.log(result); // "Bu operatsiya muvaffaqiyatli tugadi!" ni cansole.log da chiqaradi });
reject
Thereject 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 });
The above is the detailed content of Javascript Promis. For more information, please follow other related articles on the PHP Chinese website!