top of page
Logo der Online Agentur mdwp

Promise

In React JS, a Promise is not a term exclusive to React, but rather, it's a part of the wider JavaScript language as a global object model. It's a way to handle asynchronous operations without blocking the main thread of execution. A Promise in JavaScript represents an operation that hasn't completed yet, but is expected to in the future.

A Promise essentially represents a value that may not be available yet. It has three states:

1. Pending: The operation is not yet complete.
2. Fulfilled/Resolved: The operation has completed and the promise has a resulting value.
3. Rejected: The operation failed for some reason.

Promises are often used when dealing with operations that are asynchronous in nature, like API calls, fetching data from a server, or any other I/O operations.

Here is a basic example of how to create and use a promise:

```
let promise = new Promise((resolve, reject) => {
let condition = /* some condition */;

if(condition) {
resolve("Promise is resolved");
} else {
reject("Promise is rejected");
}
});

promise
.then(value => {
console.log(value); // if promise is resolved successfully
})
.catch(error => {
console.log(error); // if there is an error
});
```

In the above code, a new Promise is created which takes two parameters, resolve and reject, which are both functions. If the given condition is true, the promise is resolved, otherwise, it's rejected.

The `then()` method is used for handling the case when the promise is resolved successfully.

The `catch()` method is used for handling errors or when the promise is rejected.

bottom of page