Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





What is await and async in NodeJs?

"await" keyword within the function, we need to add "async" keyword in front of the function. The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code.

File Name :

result = await expression

expression :- A Promise or any value to wait for.

result :- Returns the fulfilled value of the promise, or the value itself if it's not a Promise.

Example

that the bcrypt.hash() function may take a while to generate the hash, and so we use the "await" keyword in front of it.

File Name :

app.post("/createUser", async (req,res) => { const user = req.body.name;
var password = req.body.password;
const hashedPassword = await bcrypt.hash(password,10); });

The await expression causes async function execution to pause until a Promise is settled and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value.

simply await the function that returns the Promise.

The await keyword is used inside the async function to wait for the asynchronous operation.

The use of await pauses the async function until the promise returns a result (resolve or reject) value.

Examples

Awaiting a promise to be fulfilled :-

If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

File Name :

function resolve_After_two_Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}

async function test() {
const a = await resolve_After_two_Seconds(10);
console.log(a); // 10
}

test();

File Name :

// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});

// async function
async function asyncFunc() {

// wait until the promise resolves
let result = await promise;

console.log(result);
console.log('hello');
}

// calling the async function
asyncFunc();

async function :-

async keyword with a function to represent that the function is an asynchronous function. The async function returns a promise.

File Name :

async function name(parameter1, parameter2, ...paramaterN) {
// statements
}

  • name - name of the function
  • parameters - parameters that are passed to the function

  • Thenable objects :-

    Thenable objects will be fulfilled just the same result.

    File Name :

    async function test() {
    const thenable = {
    then(resolve, _reject) {
    resolve('resolved!')
    }
    };
    console.log(await thenable); // resolved!
    }

    test();

    Example: After async/await

    File Name :

    async function show(req, res){
    let response = await request.get('http://ittutorial.in');
    if (response.err)
    {
    console.log('error');
    }
    else
    {
    console.log('fetched response');
    }
    }

    The above code asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.

    Promise

    In JavaScript, a promise is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not.

    A promise may have one of three states.

  • Pending
  • Fulfilled
  • Rejected
  • A promise starts in a pending state. That means the process is not complete. If the operation is successful, the process ends in a fulfilled state. And, if an error occurs, the process ends in a rejected state.

    File Name :

    For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will be in a fulfilled state. If an error occurs, then it will be in a rejected state.


    Create a Promise

    To create a promise object, we use the Promise() constructor.

    File Name :

    let promise = new Promise(function(resolve, reject){
    //do something
    });

    The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and reject().

    If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.

    File Name :


    Example:-

    const count = 5;

    let result = new Promise(function (resolve, reject) {
    if (count) {
    resolve("success");
    } else {
    reject("error occurs");
    }
    });

    console.log(result );

    Output :-

    Promise {: "success."}

    File Name :


    Promise Chaining

    Promises are useful when you have to handle more than one asynchronous task, one after another.

    You can perform an operation after a promise is resolved using methods then(), catch() and finally().

    then() method

    File Name :

    The then() method is used with the callback when the promise is successfully fulfilled or resolved.

    The syntax of then() method is:

    promiseObject.then(onFulfilled, onRejected);

    Example 2: Chaining the Promise with then()

    File Name :

    // returns a promise value

    let res_obj = new Promise(function (resolve, reject) {
    resolve("Promise resolved");
    });

    // executes when promise is resolved successfully

    res_obj
    .then(function successValue(result) {
    console.log(result);
    })

    .then(function successValue1() {
    console.log("You can call multiple functions this way.");
    });

    Output :-

    Promise resolved
    You can call multiple functions this way.

    JavaScript catch() method

    The catch() method is used with the callback when the promise is rejected or if an error occurs.

    File Name :

    // returns a promise
    let countValue = new Promise(function (resolve, reject) {
    reject('Promise rejected');
    });

    // executes when promise is resolved successfully
    countValue.then(
    function successValue(result) {
    console.log(result);
    },
    )

    // executes if there is an error
    .catch(
    function errorValue(result) {
    console.log(result);
    }
    );

    File Name :


    JavaScript Promise Methods

    File Name :






    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here