gen-thread/example.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

var gen = require('./index.js');
2016-06-27 16:03:06 +03:00
function* test()
2016-06-27 16:03:06 +03:00
{
console.log('start');
// Should give no "Generator is already running" error
var v = yield gen.cb()('expected value');
console.log(v[0] === 'expected value');
var cb = gen.unsafe();
console.log([ 'next', yield setTimeout(function() { cb('zhopa', 123); }, 500) ]);
2016-06-27 16:03:06 +03:00
var args = yield gen.runParallel([
(function*()
2016-06-27 16:03:06 +03:00
{
var cb = gen.unsafe();
yield setTimeout(function() { cb('callback 1'); }, 500);
2016-06-27 16:03:06 +03:00
return 'result 1';
})(),
(function*()
2016-06-27 16:03:06 +03:00
{
var cb = gen.unsafe();
yield setTimeout(function() { cb('callback 2'); }, 500);
2016-06-27 16:03:06 +03:00
return 'result 2';
})()
], gen.cb());
2016-06-27 16:03:06 +03:00
console.log('abc');
console.log(args);
return 'result';
}
function* test_throttle()
2016-07-17 00:35:35 +03:00
{
yield gen.throttle(5);
2016-07-17 00:35:35 +03:00
console.log('at most 5');
yield setTimeout(gen.cb(), 1000);
2016-07-19 13:38:35 +03:00
console.log('continue in another generator');
yield* other_gen(); // same as 'yield gen.run(other_gen, gen.cb())'
2016-07-19 13:38:35 +03:00
}
function* other_gen()
2016-07-19 13:38:35 +03:00
{
yield setTimeout(gen.cb(), 1000);
2016-07-19 13:38:35 +03:00
console.log('finished in another generator');
2016-07-17 00:35:35 +03:00
}
function* test_throw()
{
var cb = gen.errorfirst();
try
{
yield setTimeout(function() { cb(new Error()); }, 500);
}
catch (e)
{
console.log('Catched '+e.stack);
}
console.log(yield setTimeout(gen.cb(), 500));
console.log('sleep');
console.log(yield setTimeout(gen.cb(), 500));
console.log('continue');
}
gen.run(test, function(result) { console.log(result); });
2016-07-22 22:54:43 +03:00
for (var i = 0; i < 15; i++) gen.run(test_throttle);
gen.run(test_throw);