Simplest Promise Example

What is a Simplest Promise Example?

A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It is a way to handle asynchronous operations such as data fetching, file I/O, network calls, etc.

A Simplest Promise Example is where we create a Promise that resolves with a value of "Hello World" after 3 seconds delay. Here's the code for it:


const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello World");
  }, 3000);
});

myPromise.then((value) => {
  console.log(value);
});

In this code, we create a new Promise using the Promise constructor. The constructor takes a function as its argument, which is called the executor function. The executor function takes two arguments, resolve and reject, which are functions that we can call to either resolve or reject the Promise.

In our example, we use the setTimeout function to simulate an asynchronous operation that takes 3 seconds to complete. After the 3 seconds are up, we call the resolve function with the value of "Hello World".

Finally, we use the then method on our Promise object to define what should happen when the Promise is resolved. In our example, we simply log the resolved value to the console.

This is just one example of how Promises can be used in JavaScript. There are many other use cases for Promises, and they can be combined with other JavaScript features such as async/await and Promise.all to create more complex asynchronous workflows.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe