2.1 Creating Promises
Promises are objects that represent the completion (or failure) of an asynchronous operation and its result. They were introduced in ES6 (ECMAScript 2015) and have become the standard way to handle async code in JavaScript.
Core Concepts
A promise can be in one of three states:
- Pending: initial state, neither fulfilled nor rejected.
- Fulfilled: operation completed successfully.
- Rejected: operation completed with an error.
Creating a Promise
A promise is created using the Promise
constructor, which accepts an executor function.
This function takes two arguments: resolve
and reject
.
Within this function, async code is executed, and resolve
is called on success,
while reject
is called on error.
Syntax:
const promise = new Promise((resolve, reject) => {
// Asynchronous operation
if (/* successful completion */) {
resolve(value); // Success
} else {
reject(error); // Error
}
});
Example of Creating a Promise:
const myPromise = new Promise((resolve, reject) => {
const success = true; // Condition for successful completion
if (success) {
resolve('Operation was successful');
} else {
reject('Operation failed');
}
});
2.2 Using Promises
then Method
The then
method is used to handle the successful completion of a promise. It accepts two functions: the first for handling
success and the second for handling errors. However, the catch
method is usually used for error handling.
Example of using then:
myPromise.then(
(successMessage) => {
console.log(successMessage); // Outputs: Operation was successful
},
(errorMessage) => {
console.error(errorMessage); // Called in case of error
}
);
catch Method
The catch
method is used for handling promise errors. It takes one function that is called
in case the promise is rejected.
Example of using catch:
myPromise
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.error(errorMessage); // Called: Operation failed
});
finally Method
The finally
method is used to execute code regardless of the promise’s outcome (success or error).
It doesn’t take any arguments and runs in any case after the promise is settled.
Example of using finally:
myPromise
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.error(errorMessage);
})
.finally(() => {
console.log('Operation completed'); // Called in any case
});
2.3 Examples of using Promises
Example 1: Asynchronous Operation using Promise
Simulation of an asynchronous operation with a timer.
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('Async operation was successful');
} else {
reject('Async operation failed');
}
}, 2000);
});
}
asyncOperation()
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log('Async operation completed');
});
Example 2: Sequential Execution with Promises
Simulation of sequential asynchronous operations.
function firstOperation() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('First operation completed');
resolve('First result');
}, 1000);
});
}
function secondOperation(result) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Second operation completed');
resolve(`Second result, received: ${result}`);
}, 1000);
});
}
firstOperation()
.then((result) => {
return secondOperation(result);
})
.then((finalResult) => {
console.log(finalResult);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log('Both operations completed');
});
Example 3: Parallel Execution with Promise.all
Simulation of parallel asynchronous operations.
function operationOne() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Operation One completed');
resolve('Result One');
}, 1000);
});
}
function operationTwo() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Operation Two completed');
resolve('Result Two');
}, 1500);
});
}
Promise.all([operationOne(), operationTwo()])
.then((results) => {
console.log('All operations completed');
console.log(results); // Outputs: ['Result One', 'Result Two']
})
.catch((error) => {
console.error('One of the operations failed', error);
});
GO TO FULL VERSION