NodeJS Promises


What are promises in Node.js?

Promises in Node.js represent the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states: pending, fulfilled, or rejected. Once a promise is fulfilled or rejected, its result or error can be handled using .then() and .catch() methods, respectively.


How do promises work in Node.js?

Promises provide a cleaner way to handle asynchronous operations compared to callbacks. A promise starts in a pending state, then either resolves (fulfilled) with a value or rejects with an error. You can chain promises using .then() for success and .catch() for error handling.

Here is an example of a promise:

const myPromise = new Promise((resolve, reject) => {
    const success = true;  // Simulating success
    if (success) {
        resolve('Operation successful!');
    } else {
        reject('Operation failed.');
    }
});

myPromise
    .then((result) => {
        console.log(result);  // 'Operation successful!'
    })
    .catch((error) => {
        console.error(error);  // Handles any rejection
    });

What are the states of a promise?

A promise can be in one of the following three states:

  • Pending: The initial state, where the promise has not yet been fulfilled or rejected.
  • Fulfilled: The operation has completed successfully, and the promise has a resolved value.
  • Rejected: The operation has failed, and the promise has been rejected with an error.

How do you create a promise in Node.js?

To create a promise, you use the Promise constructor, which takes a function (executor) with two parameters: resolve and reject. The resolve function is called when the operation is successful, and reject is called if it fails.

Example of creating a simple promise:

const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
        resolve('Promise resolved successfully.');
    } else {
        reject('Promise rejected.');
    }
});

To handle the result of the promise, you use the .then() method:

myPromise
    .then((result) => {
        console.log(result);  // 'Promise resolved successfully.'
    })
    .catch((error) => {
        console.error(error);  // 'Promise rejected.'
    });

What is the difference between .then() and .catch() in promises?

.then() is used to handle the successful completion of a promise, while .catch() is used to handle any errors or rejections. Both methods return a promise, enabling chaining.

For example:

const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
        resolve('Operation successful.');
    } else {
        reject('Operation failed.');
    }
});

myPromise
    .then((result) => {
        console.log(result);  // 'Operation successful.'
    })
    .catch((error) => {
        console.error(error);  // 'Operation failed.'
    });

What is promise chaining?

Promise chaining allows you to execute a sequence of asynchronous operations by returning a new promise in the .then() method. The result of one promise is passed as input to the next promise in the chain. This is useful for running multiple asynchronous tasks in order.

Example of promise chaining:

const promiseChain = new Promise((resolve) => {
    resolve(1);
});

promiseChain
    .then((value) => {
        console.log(value);  // 1
        return value * 2;
    })
    .then((value) => {
        console.log(value);  // 2
        return value * 3;
    })
    .then((value) => {
        console.log(value);  // 6
    });

How do you handle errors in promises?

Errors in promises are handled using the .catch() method. If any of the promises in a chain reject, the error is propagated down the chain until it is caught by a .catch() handler. This makes it easy to handle errors in a centralized manner.

Example of error handling in promises:

const myPromise = new Promise((resolve, reject) => {
    const success = false;
    if (success) {
        resolve('Operation successful.');
    } else {
        reject('Operation failed.');
    }
});

myPromise
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error('Error:', error);  // 'Error: Operation failed.'
    });

What is Promise.all() in Node.js?

Promise.all() is a method that takes an array of promises and returns a single promise that resolves when all the promises in the array resolve. If any of the promises are rejected, Promise.all() rejects with the reason of the first rejected promise.

Example of Promise.all():

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);

Promise.all([promise1, promise2, promise3])
    .then((values) => {
        console.log(values);  // [1, 2, 3]
    })
    .catch((error) => {
        console.error('Error:', error);
    });

What is Promise.race() in Node.js?

Promise.race() is a method that takes an array of promises and returns a single promise that resolves or rejects as soon as one of the promises resolves or rejects. The result or error of the first promise to settle is used for the final resolution.

Example of Promise.race():

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'One'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 50, 'Two'));

Promise.race([promise1, promise2])
    .then((result) => {
        console.log(result);  // 'Two' - because promise2 settles first
    });

What is async/await in Node.js, and how does it relate to promises?

async/await is syntactic sugar built on top of promises, allowing you to write asynchronous code that looks more like synchronous code. With async/await, you can use the await keyword to pause the execution of an asynchronous function until a promise is resolved or rejected, making it easier to read and maintain asynchronous code.

Example of using async/await with promises:

function asyncTask() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Task complete');
        }, 1000);
    });
}

async function runAsync() {
    try {
        const result = await asyncTask();
        console.log(result);  // 'Task complete'
    } catch (error) {
        console.error('Error:', error);
    }
}

runAsync();
Ads