javascript - Meteor js 回调不起作用

标签 javascript asynchronous meteor callback

我在 Meteor 异步方法中设置了一个回调函数,以便在“可读”事件时调用。但是当 on."readed"被触发时,回调不会被调用(我知道它是从我设置的 console.log 中触发的)。

我在这里遗漏了什么吗?我已经花了几个小时了,现在正在尝试一些不同的事情!

Meteor.startup(() => {

  Meteor.call("getfeed", function(feedloader) {
    //I get: TypeError: undefined is not a function]
    console.log(feedloader);
  });

});

Meteor.methods({

  getfeed: function(callb) {

    var req = request('http://feeds.feedburner.com/Techcrunch');
    var feedparser = new FeedParser();
    testing = [];

    //........a bunch of functions........

    feedparser.on('readable', function() {

      var stream = this
        , meta = this.meta
        , item;

      while (item = stream.read()) 
      {
        //I'm pushing the results into testing var
        testing.push(item);
      }

      //From the logs I can see that this is called 12 times
      //but the callback's not firing!!!

      console.log(testing.length);
      callb(testing);

    });
  }
});

最佳答案

Meteor 方法不是异步函数,因为即使您在“调用”方法时传递了回调参数,它们也不会获得回调参数。相反,每个方法都在Fiber 中执行,这是处理异步代码的另一种风格。

幸运的是,Meteor 有一个很好的 helper ,可以让你混合两种风格。您需要做的是使用 Meteor.wrapAsync 包装方法代码的“纯”异步部分。这个结构应该看起来或多或少像这样:

Meteor.methods({

  getfeed: function() {
    var wrapped = Meteor.wrapAsync(function (callb) {

      var feedparser = new FeedParser();
      testing = [];

      // ...

      feedparser.on('readable', function() {
        // probably the same code you have, but without "callb()"
      });

      feedparser.on('end', function () {
        // NOTE: No error here, so the first argument must be null.
        callb(null, testing);
      })
    });

    // NOTE: Finally, call the wrapped function
    return wrapped();
  }
});

关于javascript - Meteor js 回调不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481308/

相关文章:

meteor - 在 meteor 中调整大小并将文件保存到 s3

javascript - 我们可以在 Javascript 中命名事件处理程序吗?

javascript - 光标移动到文本字段的开头

javascript - 使用 JS 或 jQuery 从列表中选择多个项目

javascript - Angular Controller 完成加载异步函数后加载 html View

javascript - SignalR 加入/离开组无法正常工作

javascript - 更改列表中 anchor 标记的类名

javascript - then() 在 Promise 之前完成

meteor 和铁路由器 : raise 404 when id doesn't exist

javascript - 无法在 meteor 应用程序上使用 setTimeout() 函数