我是 Node.js 的新手,我意识到它和客户端 javascript 的最大区别之一是 一切 都是异步的。
为了尝试解决这个问题,我尝试使用 fibrous将我的代码转回更函数式的编程风格,但有一些问题:
我怎样才能让下面的 fibrous 代码起作用?
例如,我希望下面的代码打印 1,2,3,但它打印的是 1,3,2
function test()
{
var fibrous = require('fibrous');
var fs = require('fs');
fibrous.run(function() {
var data = fs.sync.readFile('/etc/passwd');
console.log('2');
});
}
function runTest()
{
console.log('1');
test();
console.log('3');
}
runTest();
// This prints 1,3,2 to the console, not 1,2,3 as I'd like.
在一个真实的用例中,上面的例程将包装一个运行异步的数据库方法,并制作它以便我可以编写如下内容:
var dbTable = new dbTableWrapper();
var data = dbTable.getData();
/*
... do things with the data.
The "getData" routine is the same as my "test" function above.
*/
最佳答案
Is the answer to run the (newly added) "runTest" routine using a fibrous.run call itself?
这是其中的一部分,是的。 Fibrous 需要自己调用 runTest
才能管理其执行。
然后,测试
就是needs to be wrapped而不是 .run()
:
var test = fibrous(function () {
var data = fs.sync.readFile('/etc/passwd');
console.log('2');
});
应该是called with .sync()
:
test.sync();
var fibrous = require('fibrous');
var fs = require('fs');
var test = fibrous(function () {
var data = fs.sync.readFile('/etc/passwd');
console.log('2');
});
function runTest() {
console.log('1');
test.sync();
console.log('3');
}
fibrous.run(runTest);
关于javascript - 如何在 Node.js 中进行纤维化等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700029/