【问题标题】:How to make fibrous wait in Node.js?如何在 Node.js 中让纤维等待?
【发布时间】:2013-09-13 01:09:16
【问题描述】:

我是 Node.js 的新手,我意识到它和客户端 javascript 的最大区别之一是异步 everything 的方式。

为了解决这个问题,我尝试使用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.

在一个真实的用例中,上述例程将包装一个运行异步的 DB 方法,并使其能够编写如下内容:

var dbTable = new dbTableWrapper();
var data = dbTable.getData();

/*
 ... do things with the data. 
 The "getData" routine is the same as my "test" function above.
*/

【问题讨论】:

  • 您正在传递fibrous.run 一个回调,其中包含您的console.log。回调总是稍后在调用堆栈中执行。你不能改变这一点。您必须移动其他两个 console.log 函数。
  • 我的意图是使用 fibrous 使异步代码同步。因此,例如,上面的内容实际上是在“dbObject.getData()”调用中,我希望能够像往常一样按功能顺序执行 DB 操作。我再澄清一点!
  • @BradParks Fibrous 不会“使其同步。”它自己管理function 的执行,在不同的点暂停和继续它。这使得该函数中的编码风格看起来是同步的,但它仍然异步执行并且对周围的代码没有影响。
  • 感谢您的反馈!我明白了......但我敢肯定,其他人想知道我问的同样的问题。使用 fibrous.run 调用本身运行(新添加的)“runTest”例程的答案是什么?
  • 尝试使用waitFor。 github.com/luciotato/waitfor

标签: javascript node.js promise node-fibers


【解决方案1】:

其他快递使用:

 var express = require('express');
 var router = express.Router();
 var fibrous = require('fibrous');

 router.use(fibrous.middleware);

 router.get('/sync', function(req, res, next) {

   var order_categories = Order_Category.sync.list(options);
   console.log("Order_Category count : " , order_categories.length);

   var content_tags = Content_Tag.sync.list(options);
   console.log("content_tags count : " , content_tags.length);

   var creatives = Creative.sync.list(options);
   console.log("creatives count : " , creatives.length);

   return res.send( {
      order_categories: order_categories,
      content_tags: content_tags,
      creatives: creatives
      }
   );

 });

【讨论】:

    【解决方案2】:

    答案是使用 fibrous.run 调用本身来运行(新添加的)“runTest”例程吗?

    这是其中的一部分,是的。 Fibrous 需要自己调用runTest 才能管理其执行。

    那么,test 只是 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);
    

    【讨论】:

    • 太棒了!这就是我所追求的。我只是试了一下,它按预期工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 2013-09-07
    • 2015-09-22
    • 2018-02-05
    • 2012-08-12
    • 2014-05-31
    • 1970-01-01
    相关资源
    最近更新 更多