JavaScript syntax syntax

I just looked at Dave Herman with a very interesting task.js. In his example, he has the following line:

var [foo, bar] = yield join(read("foo.json"), read("bar.json")).timeout(1000); 

I am familiar with generators, but I do not understand how the yield expression evaluates what can be assigned [foo, bar]. In fact, I would not expect the expression to be assigned to anything, since it basically matches the return.

The output syntax for JS still seems a bit underestimated, and I could not find any information about it.

So, to clarify my question: what is foo and bar ultimately assigned to?

+6
source share
2 answers

Actually, the corresponding paragraph is a little lower in https://developer.mozilla.org/En/New_in_JavaScript_1.7 :

Once the generator has been started by calling its next() method, you can use send() , passing a specific value, which will be considered as the result of the last yield . Then the generator will return the operand of the subsequent yield .

I think this makes sense only if the generator is used by calling its methods directly, and not when cycling its values ​​- the cycle will always call next() on the generator and never send() .

In a sense, running a generator is similar to collaborative multitasking. The generator runs until a yield is found. It returns control to those who called next() or send() on the generator. Then the caller continues execution until the next call to next() or send() is made - now the generator starts again. Each time values ​​can be passed back and forth.

Here is a simple example:

 function gen() { var [foo, bar] = yield 1; console.log("Generator got: " + foo + ", " + bar); } // This creates a generator but doesn't run it yet var g = gen(); // Starts generator execution until a yield statement returns a value var result = g.next() console.log("Received from generator: " + result); // Continue generator execution with [2, 3] being the return value // of the yield statement. This will throw StopIteration because the // iterator doesn't have any more yield statements. g.send([2, 3]); 
+6
source

https://developer.mozilla.org/En/New_in_JavaScript_1.7

A function containing the yield keyword is a generator. When you call it, its formal parameters are tied to the actual arguments, but its body is not actually evaluated. Instead, an iterator generator is returned. Each call to the generator-iterator next () method performs a different pass through an iterative algorithm. Each step value is the value indicated by the yield keyword. Think of the output as a return-generator-iterator version, specifying the boundary between each iteration of the algorithm. Each time you call next (), the generator code is resumed from the instruction following the exit.

0
source

Source: https://habr.com/ru/post/894858/


All Articles