In this article, we will see how Await keyword is different from Yield keywords.
Generator Functions: Functions that can return multiple values at different time interval as per the user demands, and can manage its internal state are generator functions. A function becomes a Generator function if it uses the function* syntax. They are different from normal functions because normal functions completion in a single run, whereas we can pause and resume the generator function.
Note: When generator functions are executed, it returns a new Generator object.
functionality: yield and await can both be used to write asynchronous code that “waits”, which means code that looks as if it was synchronous, even though it really is asynchronous.
When we use 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.
var result = await expression;
expression: A Promise or any value to wait for.
result: contains the value of promise(resolved value).
(note: run the above code in node.js)
yield: The yield keyword is used to pause and resume a generator function.
The keyword yield 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.
It causes the call to the generator’s next() method to return an IteratorResult object with two properties:
- value: It is the value returned by the yield keyword.
- done: it is of boolean type. (if done is false, it means that the generator function has not been fully completed).
Using it, we can create an iterator for traversing data.
var result = yield expression;
expression: the value to return from the generator function.
result: Retrieves the optional value passed to the generator’s next() method to resume its execution.
Please Login to comment...