Node.js Callbacks, Promises and Async/Await

Aim

To demonstrate Callbacks, Promises and Async/Await in Node.js.

1. Callback

A callback is a function passed as an argument to another function.

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

greet("Madhu", function() {
    console.log("Callback executed");
});
    

2. Promise

A Promise represents the result of an asynchronous operation.

const promise = new Promise((resolve, reject) => {
    resolve("Promise completed successfully");
});

promise.then(result => {
    console.log(result);
});
    

3. Async/Await

Async/Await is used to write asynchronous code in a simple way.

async function showMessage() {
    const message = await Promise.resolve("Async/Await completed");
    console.log(message);
}

showMessage();
    

Expected Output

Hello Madhu
Callback executed
Promise completed successfully
Async/Await completed