top of page
Logo der Online Agentur mdwp

Promises

Promises in React JS, are similar to promises in real life. They are a mechanism that makes handling asynchronous operations, such as API calls, timer functions, or any code that takes time to execute, much simpler and more efficient. Much like a person promising to do something in the future, a JavaScript Promise is a placeholder for a future value.

In other terms, a Promise in JavaScript (and therefore React) is an object representing the eventual completion or failure of an asynchronous operation. It serves as a link between the executing functions and the functions that will be triggered once the value is computed or once an error occurs.

Once a Promise is made, it will be in one of three states:
- Pending: The Promise's outcome hasn't yet been determined, because the asynchronous operation that will produce its result hasn't completed yet.
- Fulfilled: The asynchronous operation has completed, and the Promise has a resulting value.
- Rejected: The asynchronous operation failed, and the Promise will never be fulfilled.

Here's an example of how you might set up a Promise:

```js
let promise = new Promise((resolve, reject) => {
// simulate an asynchronous operation
setTimeout(() => {
// once the operation is completed, call resolve to mark
// the promise as fulfilled
resolve('Operation completed');
}, 2000);
});

promise.then(result => {
// The 'then' method is called when the Promise is resolved (fulfilled).
// The resolved value is passed as an argument
console.log(result); // "Operation completed"
}).catch(error => {
// If something went wrong and the Promise got rejected, we handle it in the 'catch' block
console.log('Error:', error);
});
```

In above code, `new Promise` creates a Promise object that wraps an asynchronous operation. The Promise constructor takes a function (called the "executor") that takes two parameters: `resolve` and `reject`, which are both functions themselves. Once the asynchronous operation inside the executor is done, we call `resolve` to signal that the Promise is fulfilled, or `reject` to indicate that the Promise couldn't be fulfilled.

bottom of page