Home > Web Front-end > JS Tutorial > body text

Promises in java script

PHPz
Release: 2024-08-21 06:04:36
Original
974 people have browsed it

Promises in java script

what is promises

*A Promises is an object representing the eventual completion of an asynchronous operation.

States of a Promise

A Promise can be in one of three states:

1.Pending: The initial state, neither fulfilled nor rejected.
2.Fulfilled: The operation completed successfully.
3.Rejected: The operation failed.

Creating a Promise

let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});

To handle the outcome of a promise, you use the then() and catch() methods:

myPromise
.then((message) => {
console.log(message); // "Operation was successful!"
})
.catch((error) => {
console.error(error); // "Operation failed."
});

*then() is executed when the promise is fulfilled.
*catch() is executed when the promise is rejected.

Example of promises

const myPromise = new Promise((resolve, reject) => {

setTimeout(() => {

    resolve("Promise fulfilled!");
}, 2000); 
Copy after login

});

myPromise
.then(message => {
console.log(message);
})
.catch(error => {
console.error('There has been a problem with the promise:', error);
});

Advantages of Promises:-

1.Improved Readability:

Promises allow for cleaner and more linear code compared to nested callbacks.

2.Better Error Handling:

Errors can be handled using a dedicated .catch() method, simplifying error management.

3.Avoids Callback Hell:

Promises help prevent deeply nested structures, making the code easier to read and maintain.

4.Supports Async/Await:

Promises are the foundation for the async/await syntax, allowing asynchronous code to be written in a synchronous style.

5.Enhanced Performance:

Promises can improve performance by allowing multiple asynchronous operations to run concurrently.

The above is the detailed content of Promises in java script. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!