function* generatorFn () {
console.log('look ma I was suspended')
}
var generator = generatorFn() // [1]
setTimeout(function () {
generator.next() // [2]
}, 2000)
function *generator() {
console.log('Start!');
var i = 0;
while (true) {
if (i < 3)
yield i++;
}
}
var gen = generator();
var ret = gen.next();
// Start!
console.log(ret);
// {value: 0, done: false}
console.log(gen.next());
// {value: 1, done: false}
console.log(gen.next());
// {value: 2, done: false}
console.log(gen.next());
// {value: undefined, done: true}
var gen = generator();
console.log(gen.next().value);
setTimeout(function() {
console.log(gen.next().value);
console.log('第一步');
}, 1000);
console.log('第二步');
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]
function* iter () {
for (var i = 0; i < 10; i++) yield i
}
for (var val of iter()) {
console.log(val) // outputs 1?—?9
}
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
}
}
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)
}
function* fibGen () {
var current = 0, next = 1, swap
while (true) {
swap = current, current = next
next = swap + next
yield current
}
}
for (var num of fibGen()) {
if (num > 5000) break
}
console.log(num) // 6765
run(function* () {
console.log("Starting")
var file = yield readFile("./async.js") // [1]
console.log(file.toString())
})
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
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有