Generators are a coroutine (coroutine for short: coroutine) style of Javascript. They refer to functions that can be paused and then resumed during execution. The function is in the functi with an asterisk symbol such as function*, function There are some characteristic keywords such as yield and yield*.
function* generatorFn () { console.log('look ma I was suspended') } var generator = generatorFn() // [1] setTimeout(function () { generator.next() // [2] }, 2000)
The [1] and [2] marked in the code are explained as follows:
1. This is a generator started in pause mode. There is no console output at this time.
2. By calling its next() method, this generator will execute and run until it encounters the next yield keyword or return. Now we have console output.
Look at another case:
function *generator() { console.log('Start!'); var i = 0; while (true) { if (i < 3) yield i++; } } var gen = generator();
The above code is similar to the first one, except that the yield keyword is added to the generator function. When the above code is called, it will not be executed immediately, but will be suspended and on standby, so there will be no Start output. It is not executed until its next() call.
var ret = gen.next(); // Start! console.log(ret); // {value: 0, done: false}
The ret above is the generator result. It has two attributes:
■value, the yield value in the generator function,
■done, this is a flag indicating whether the generator function returns.
The continuation code is as follows:
console.log(gen.next()); // {value: 1, done: false} console.log(gen.next()); // {value: 2, done: false} console.log(gen.next()); // {value: undefined, done: true}
Generator has no mystery in synchronous programming, and is especially suitable for asynchronous programming.
generator has two characteristics:
1. You can choose to jump out of a function and let the external code decide when to jump back to this function to continue execution.
2. Ability to perform asynchronous control.
Look at the asynchronous execution code below:
var gen = generator(); console.log(gen.next().value); setTimeout(function() { console.log(gen.next().value); console.log('第一步'); }, 1000); console.log('第二步');
The output is:
0
Step 2
1
The first step
In other words, you will not wait for the end of the timer in setTimeout, but continue directly to the "second step" and will not be blocked in setTimeout.
Look at another piece of code:
function* channel () { var name = yield 'hello, what is your name?' // [1] return 'well hi there ' + name } var gen = channel() console.log(gen.next().value) // hello, what is your name? [2] console.log(gen.next('billy')) // well hi there billy [3]
You can also use *:
when traversing
function* iter () { for (var i = 0; i < 10; i++) yield i } for (var val of iter()) { console.log(val) // outputs 1?—?9 }
Common misunderstandings
Since I can pause the execution of a function, should I let them execute in parallel? No, because Javascript is single-threaded, and if you are looking to improve performance, generators are not your cup of tea.
For example, the following code executes Fibonacci numbers respectively:
function fib (n) { var current = 0, next = 1, swap for (var i = 0; i < n; i++) { swap = current, current = next next = swap + next } return current } function* fibGen (n) { var current = 0, next = 1, swap for (var i = 0; i < n; i++) { swap = current, current = next next = swap + next yield current } }
The performance results are as follows: (the higher, the better)
results:
regular 1263899
generator 37541
Generators shine
Generators can simplify the complexity of functions in JavaScript.
Lazy assignment
Although lazy assignment can be implemented using JS closures, using yield will greatly simplify it. By pausing and resuming, we can get the value when we need it. For example, the fibGen function above can pull it when we need it. New value:
var fibIter = fibGen(20) var next = fibIter.next() console.log(next.value) setTimeout(function () { var next = fibIter.next() console.log(next.value) },2000) 当然还使用for循环:依然是懒赋值 for (var n of fibGen(20) { console.log(n) }
Infinite Sequence
Because lazy assignment is possible, it is possible to perform some Haskell tricks, similar to infinite sequences. Here you can yield an infinite number of sequences.
function* fibGen () { var current = 0, next = 1, swap while (true) { swap = current, current = next next = swap + next yield current } }
Let’s look at the lazy assignment of a Fibonacci number stream and ask it to return the first Fibonacci number after 5000:
for (var num of fibGen()) { if (num > 5000) break } console.log(num) // 6765
Asynchronous process control
Use generators to implement asynchronous process control. The most common ones are various promise library packages. So how does it work?
In the field of Node, everything is related to callbacks, which are our low-level asynchronous functions. We can use generators to establish a communication channel and write asynchronous code using a synchronous programming style.
run(function* () { console.log("Starting") var file = yield readFile("./async.js") // [1] console.log(file.toString()) })
Comment 1 indicates that the program will wait for async.js to return the result before continuing.
Genify is a framework that brings generators into the normal programming environment. It is used as follows:
npm install genify to install, the code is as follows:
var Q = require('q'); var fs = require('fs'); var genify = require('genify'); // wrap your object into genify function var object = genify({ concatFiles: function * (file1, file2, outFile) { file1 = yield Q.nfcall(fs.readFile, file1); file2 = yield Q.nfcall(fs.readFile, file2); var concated = file1 + file2; yield Q.nfcall(fs.writeFile, outFile, concated); return concated; } }); // concatFiles是一个generator函数,它使用generator强大能力。 object.concatFiles('./somefile1.txt', './somefile2.txt', './concated.txt').then(function (res) { // do something with result }, function (err) { // do something with error });
The above detailed explanation of using Javascript Generators in Node.js is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.