how to create a promise in javascript

To create a Promise in JavaScript, you can use the Promise constructor which takes a function that has two parameters: resolve and reject. The resolve parameter is called when the promise is successfully completed, and the reject parameter is called when there is an error during its execution.

Here's an example of creating a Promise that resolves after one second:

index.tsx
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise is fulfilled!');
  }, 1000);
});

myPromise.then((result) => {
  console.log(result); // Promise is fulfilled!
});
210 chars
10 lines

In this example, we use the setTimeout function to simulate a delay of one second before resolving the Promise with the message 'Promise is fulfilled!'. We then use the then() method of the Promise to log the result to the console.

Promises are a useful tool for managing asynchronous code in JavaScript, and they work well with async/await and callbacks to create more readable and maintainable code.

gistlibby LogSnag