How to create a new Promise in JavaScript? Give an example.
How to create a new Promise in JavaScript? Give an example.
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
Creating 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.