javascript - 如何在 Node.js 中进行纤维化等待?

标签 javascript node.js promise node-fibers

我是 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/

相关文章:

javascript - Twitter Digits - 使用 AngularJS 检索用户帐户数据

node.js - Mongoose 插件将额外数据分配给字段但不保存到数据库

node.js - 尝试连接到 Azure 中的 API 但允许来源时出错

javascript - 如何异步多次调用 promise 函数以用给定数量的值填充数组?

javascript - 定时 promise 队列/节流

javascript - Vue.js 应该在浏览器的 devtools 中看到在路由器 View 上传递的 prop 数据吗?

javascript - 获取某些复选框的 ID 并禁用它们

javascript - NodeJS 中循环嵌套 Json 数据

node.js - Mongoose 搜索多个字段

node.js - Bluebird promise 和回调,没有错误参数