【发布时间】:2013-01-29 01:06:12
【问题描述】:
我有一个关于 Nodejs Fibers 的问题(这对我来说绝对是新的)...... 我有这个 Nodejs Fibers 教程,http://bjouhier.wordpress.com/2012/03/11/fibers-and-threads-in-node-js-what-for/,这里有一个例子,上面写着
var fiber = Fiber.current;
db.connect(function(err, conn) {
if (err) return fiber.throwInto(err);
fiber.run(conn);
});
// Next line will yield until fiber.throwInto
// or fiber.run are called
var c = Fiber.yield();
// If fiber.throwInto was called we don't reach this point
// because the previous line throws.
// So we only get here if fiber.run was called and then
// c receives the conn value.
doSomething(c);
// Problem solved!
现在基于这个示例,我创建了自己的代码版本,如下所示,
var Fiber = require('fibers');
function sample(callback){
callback("this callback");
}
var fiber = Fiber.current;
sample(function(string){
fiber.run(string);
});
var string = Fiber.yield();
console.log(string);
但这给了我一个错误,
/home/ubuntu/Tasks/ServerFilteringV1/test.js:28
fiber.run(string);
^
TypeError: Cannot call method 'run' of undefined
我还有另一个案例,它会在 1000 毫秒后运行一个函数,里面有回调(我这样做是为了在回调之前测试长时间执行的函数),
var Fiber = require('fibers');
function forEach(callback){
setTimeout(function(){
callback("this callback");
},1000);
}
var fiber = Fiber.current;
forEach(function(string){
fiber.run(string);
});
var string = Fiber.yield();
console.log(string);
这里的代码给了我另一个错误,
/home/ubuntu/Tasks/ServerFilteringV1/test.js:30
var string = Fiber.yield();
^
Error: yield() called with no fiber running
那么,yield() 是否应该在 run() 函数执行后等待? 关于我的 nodejs 代码中发生了什么的任何想法? 并提前感谢...
【问题讨论】:
标签: javascript node.js node-fibers