Middle+
Tell me about promises: states, methods, async/await.
sobes.tech AI
Answer from AI
Promises in JavaScript are objects that represent the result of an asynchronous operation and can be in one of three states:
- Pending — initial state, the operation is not yet completed.
- Fulfilled — the operation completed successfully, with a result.
- Rejected — the operation failed with an error.
Main methods of promises:
.then(onFulfilled, onRejected)— adds handlers for success and error results..catch(onRejected)— adds a handler for errors (equivalent to.then(null, onRejected))..finally(onFinally)— called in any case after the promise is settled.
async/await — syntactic sugar over promises, allowing writing asynchronous code in a synchronous style. A function declared with async always returns a promise. The await keyword pauses the execution of the function until the promise is settled.
Example:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data received'), 1000);
});
}
async function getData() {
try {
const result = await fetchData();
console.log(result); // 'Data received'
} catch (error) {
console.error('Error:', error);
}
}
getData();
This approach simplifies reading and handling asynchronous operations.