0
0
Javascriptprogramming~5 mins

Why promises are used in Javascript

Choose your learning style9 modes available
Introduction

Promises help manage tasks that take time, like loading data from the internet, without stopping the whole program. They make it easier to work with these tasks and handle results or errors smoothly.

When you want to get data from a website without freezing the page.
When you need to wait for a file to load before using it.
When you want to run several tasks one after another, but only after the previous one finishes.
When you want to handle errors from tasks that take time, like network requests.
Syntax
Javascript
new Promise((resolve, reject) => {
  // do something asynchronous
  if (success) {
    resolve(result);
  } else {
    reject(error);
  }
});

resolve is called when the task finishes successfully.

reject is called when the task fails or has an error.

Examples
This promise waits 1 second, then finishes successfully with 'Done!'.
Javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Done!'), 1000);
});
This promise waits 1 second, then finishes with an error.
Javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => reject('Error happened'), 1000);
});
Sample Program

This program creates a promise that waits 1 second, then resolves with a success message. It prints the message when done.

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

myPromise
  .then(result => console.log(result))
  .catch(error => console.log(error));
OutputSuccess
Important Notes

Promises let your program keep running while waiting for slow tasks.

You can use .then() to get the result and .catch() to handle errors.

Promises help avoid confusing nested callbacks, making code easier to read.

Summary

Promises handle tasks that take time without stopping the program.

They provide a clear way to get results or errors from these tasks.

Using promises makes your code cleaner and easier to understand.