Affiliate link

Node.js Functions - Promises

Promises are a more advanced form of asynchronous programming in Node.js. Promises represent the eventual completion (or failure) of an asynchronous operation and allow us to write asynchronous code in a more synchronous style.

function add(a, b) {
    return new Promise(function(resolve, reject) {
        const sum = a + b;
        if (sum >= 0) {
            resolve(sum);
        } else {
            reject("Sum is negative");
        }
    });
}

add(2, 3)
    .then(function(result) {
        console.log(result); // prints 5
    })
    .catch(function(error) {
        console.error(error); // prints "Sum is negative"
    });

Async/Await

Async/await is a newer feature of Node.js that allows us to write asynchronous code in a more synchronous style. Async/await is built on top of promises and provides a more concise and readable syntax for handling asynchronous operations.

async function add(a, b) {
    const sum = a + b;
    if (sum >= 0) {
        return sum;
    } else {
        throw new Error("Sum is negative");
    }
}

async function main() {
    try {
        const result = await add(2, 3);
        console.log(result); // prints 5
    } catch (error) {
        console.error(error); // prints "Sum is negative"
    }
}
  
main();
Affiliate link
Affiliate link
Advertisment
Ad - SiteGround Web Hosting - Crafted for easy site management. Amazing Speed; Powerful Tools; Top-rated support. Learn more.