0
0
Javascriptprogramming~5 mins

Creating promises in Javascript

Choose your learning style9 modes available
Introduction

Promises help you handle tasks that take time, like loading data. They let your program wait for the task to finish without stopping everything.

When you want to load data from the internet and wait for it to arrive.
When you need to do something after a timer finishes.
When you want to run a task that might succeed or fail and handle both cases.
When you want to avoid freezing the screen while waiting for a task.
Syntax
Javascript
const myPromise = new Promise((resolve, reject) => {
  // do something asynchronous
  const success = true; // example condition
  if (success) {
    resolve(result); // task finished successfully
  } else {
    reject(error); // task failed
  }
});

resolve is called when the task finishes well.

reject is called when the task fails.

Examples
This promise immediately finishes successfully with the message 'Done!'.
Javascript
const promise = new Promise((resolve, reject) => {
  resolve('Done!');
});
This promise waits 1 second, then finishes successfully.
Javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Waited 1 second');
  }, 1000);
});
This promise finishes with an error if error is true.
Javascript
const promise = new Promise((resolve, reject) => {
  const error = true;
  if (error) {
    reject('Something went wrong');
  } else {
    resolve('All good');
  }
});
Sample Program

This program creates a promise that finishes successfully. It then prints the success message.

Javascript
const myPromise = new Promise((resolve, reject) => {
  const success = true;
  if (success) {
    resolve('Task completed successfully');
  } else {
    reject('Task failed');
  }
});

myPromise
  .then(message => {
    console.log('Success:', message);
  })
  .catch(error => {
    console.log('Error:', error);
  });
OutputSuccess
Important Notes

Promises always run the code inside immediately when created.

Use then to handle success and catch to handle errors.

Promises help keep your program responsive by not blocking other code.

Summary

Promises represent tasks that finish later with success or failure.

You create a promise with new Promise((resolve, reject) => { ... }).

Call resolve when done well, reject when there is an error.