Skip to main content

Command Palette

Search for a command to run...

Why to use and when to use promises in JS

Updated
2 min read

Promises are especially valuable in scenarios where we need to manage asynchronous operations that have dependencies, need to execute tasks sequentially or require error handling

Let's see some of the use cases of promises so that you will understand when to use and why to use

  1. HTTP Requests: Promises are commonly used when making HTTP requests in web applications. You can use libraries like Axios or the Fetch API, both of which return promises to handle responses and errors.

     // Simulate an asynchronous data fetching operation
     function fetchDataFromServer() {
       return new Promise((resolve, reject) => {
         // Simulate a delay (e.g., an HTTP request)
         setTimeout(() => {
           const success = Math.random() < 0.8; // Simulate success most of the time
           if (success) {
             resolve('Data fetched successfully');
           } else {
             reject('Failed to fetch data');
           }
         }, 1000); // Simulate a 1-second delay
       });
     }
    
     fetchDataFromServer()
       .then((data) => {
         console.log('Success:', data);
       })
       .catch((error) => {
         console.error('Error:', error);
       });
    

    from the above code we have used resolve and reject, resolve is called when the promise is successfully fulfilled, and reject is called when the promise is unfulfilled

  2. File I/O: When reading or writing files asynchronously, promises help ensure that you can handle file operations elegantly.

     const fs = require('fs/promises');
    
     fs.readFile('file.txt', 'utf8')
       .then((data) => {
         // Handle the file content
       })
       .catch((error) => {
         // Handle file read errors
       });
    
  3. Database Operations: Promises are frequently used in database interactions. When querying a database, you can wrap the query operation in a promise.

const db = require('my-database-library');

db.query('SELECT * FROM users')
  .then((result) => {
    // Handle the query result
  })
  .catch((error) => {
    // Handle database query errors
  });

If you're wondering where we are using the promises from the above file and database examples, in both examples we are consuming the promises which are given in the form of response, and in the examples actually we are handling the operations using then and catch, if it is resolved then we will get the data into the then else catch

If hope you got something from my explanation, I will try to improve my way of explaining in every post. Please shoot your difficult topic in javascript and Golang I will try my best to make you understand confortable with it

Thank you