Async...await in Promises. JavaScript examples open

Async...await in Promises. JavaScript examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: ES6
1

The async and await operators are designed to make it easier to work with promises

The async statement defines an asynchronous function that is expected to execute one or more asynchronous tasks:

    async function functionName() {
        // asynchronous operations
    }

Inside an asynchronous function, we can use the await operator. It is placed before the invocation of an asynchronous operation that represents a Promise object:

    async function functionName() {

        await asynchronous operation();
    }

The await operator suspends the execution of an asynchronous function until the Promise object has returned a result.

The await operator can only be used inside the function to which the async operator is applied.

Let’s look at an example:

    function sum(x, y) {
        return new Promise(function (resolve) {
            const result = x + y;
            resolve(result);
        });
    }

    sum(5, 3).then(function (value) {
        console.log("Result of asynchronous operation:", value);
    }); //Result of asynchronous operation: 8

In this case, the sum() function represents an asynchronous task. It takes two numbers and returns a Promise object that adds the numbers.

The result of the addition is passed to the resolve() function. And then in the then() method, we can get this result and perform various actions with it.

Now let’s rewrite this example using async/await:

    function sum(x, y) {
        return new Promise(function (resolve) {
            const result = x + y;
            resolve(result);
        });
    }

    async function calculate() {//define an asynchronous function
        const value = await sum(5, 3);
        console.log("Result of asynchronous operation:", value);
    }
    calculate();  //Result of asynchronous operation: 8

Thanks to the await operator, there is no longer a need to call the then() method on the promise. And the result that returns Promise, we can get directly from the sum function call and, for example, assign to a constant or variable:

const value = await sum(5, 3);

Execute a sequence of asynchronous operations

An asynchronous function can contain many asynchronous operations to which the await operator is applied. In this case, all asynchronous operations will be executed sequentially:

    function sum(x, y) {
        return new Promise(function (resolve) {
            const result = x + y;
            resolve(result);
        });
    }

    async function calculate() {
        const value1 = await sum(5, 3);
        console.log(value1);
        const value2 = await sum(6, 4);
        console.log(value2);
    }
    calculate();
// Result of 1 asynchronous operation: 8
// Result of 2 asynchronous operation: 10

Error processing

The try..catch..finally construct is used to handle errors that may occur during the call of an asynchronous operation.

For example, take the following code using Promise:

    function square(str) {
        return new Promise((resolve, reject) => {
            const n = parseInt(str);
            if (isNaN(n)) reject("Not a number");
            else resolve(n * n);
        });
    };
    function calculate(str) {

        square(str)
            .then(value => console.log("Result: ", value))
            .catch(error => console.log(error));
    }

    calculate("g8");    // Not a number 
    calculate("4");     // Result:  16

When you call the square() function with the catch() method, you can handle the error that occurs.

Now let’s rewrite the example using async/await:

    function square(str) {
        return new Promise((resolve, reject) => {
            const n = parseInt(str);
            if (isNaN(n)) reject("Not a number");
            else resolve(n * n);
        })
    };

    async function calculate(str) {

        try {
            const value = await square(str);
            console.log("Result: ", value);
        }
        catch (error) {
            console.log(error);
        }
    }

    calculate("g8");    // Not a number 
    calculate("4");     // Result:  16

0

More

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation