Fix for callbacks called synchronously before yield

master
Vitaliy Filippov 2016-08-16 15:14:44 +03:00
parent 006193174f
commit 7912f93f13
2 changed files with 30 additions and 3 deletions

View File

@ -1,8 +1,11 @@
var gen = require('./gen-thread.js');
var gen = require('./index.js');
function* test()
{
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) ]);
var args = yield gen.runParallel([

View File

@ -30,11 +30,16 @@ module.exports.throttle = function(count)
function runThread(generator, onsuccess, onerror)
{
var thread = function() { continueThread.apply(thread, arguments) };
var thread = function()
{
thread._current = null;
continueThread.apply(thread, arguments);
};
thread._gen = generator.next ? generator : generator();
thread._finishThrottleQueue = finishThrottleQueue.bind(thread);
thread._onsuccess = onsuccess;
thread._onerror = onerror;
thread._running = false;
callGen(thread, 'next', []);
return thread;
}
@ -52,16 +57,35 @@ function getStack(fn)
function callGen(thread, method, arg)
{
if (thread._running)
{
// callback called while generator is already running
thread._result = [ method, arg ];
return;
}
var v;
thread._running = true;
current = thread;
try
{
v = thread._gen[method](arg);
while (1)
{
v = thread._gen[method](arg);
if (!v.done && thread._result)
{
method = thread._result[0];
arg = thread._result[1];
thread._result = null;
}
else
break;
}
}
catch (e)
{
v = { error: e };
}
thread._running = false;
current = null;
if (v.done || v.error)
{