What is the difference between the await keyword and the yield keyword?

Forums JavaScriptWhat is the difference between the await keyword and the yield keyword?
Staff asked 3 years ago

Answers (1)

Add Answer
Staff answered 3 years ago

await keyword :

use the await keyword in an expression so, the async function execution will get paused until the promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfilment. When resumed, the value of the await expression is that of the fulfilled Promise.

await  Ex:

<script>
    function calculate(y) {
        var promise = new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve(calculateSquare(y));
            }, 3000);
        });
        return promise;
    }

    function calculateSquare(y) {
        return y * y;
    }
    async function main() {
        var s1 = await calculate(5);
        //After 3 sec this line will get execute
        console.log("Square of 5 is : " + s1);
        var s2 = await calculate(10);


        // After 3 sec next this line will get execute
        console.log("Square of 10 is : " + s2);
         // In last this line will get execute
        console.log("End");
    }
   
</script>

yield keyword :

yield  keyword  is used to pause the generator function execution, and the final value of the expression will be the value followed by the yield keyword is returned to the generator’s caller.

yield Ex :

<script>
    function getValues(start, end) {
        while (start <= end) {
            yield start;
            start++;
        }
    }

    /* Expression */
    var it = getValues(5, 10);
    //element : {value : Object ,done : boolean}
    var element = it.next();

    while (element.done == false) {
        console.log(element);
        element = it.next();
    }

    // value:undefined, and done : false 
    console.log(element);
        // because element.done == true
</script>

Subscribe

Select Categories