How to create a new Promise in JavaScript? Give an example.
How to create a new Promise in JavaScript? Give an example.
320
26-Sep-2023
Updated on 26-Sep-2023
Aryan Kumar
26-Sep-2023Creating a new Promise in JavaScript involves using the Promise constructor. Here's an example of how to create a new Promise:
In this example, we create a new Promise called myPromise. It takes a function as its argument, which receives two parameters: resolve and reject. Inside this function, you define your asynchronous operation, which in this case is simulated using setTimeout.
If the operation is successful, you call resolve and pass the result to it. If it encounters an error, you call reject and provide an error message or an error object.
You can then use the .then() method to handle the successful outcome when the Promise is resolved and the .catch() method to handle errors when the Promise is rejected.