让流星方法同步 [英] Make Meteor method synchronous

查看:137
本文介绍了让流星方法同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图使该功能同步。我读过有关异步数堆栈溢出的职位,但我无法COM prehend我将如何能够使这个同步的。截至目前,它是异步的,因此它返回标题进入回调函数之前不确定的。

I've been attempting to make this function synchronous. I've read several Stack Overflow posts about Async but I'm unable to comprehend how I would be able to make this synchronous. As of now, it is asynchronous therefore it returns undefined before heading into the callback function.

我把它从客户端:

Meteor.call('screenName',function(error,result) {
        if (error) {
          console.log(error);
        }
        else {
          window.alert(result);
        }
      }

这是服务器端的方法:

And this is the server side method:

Meteor.methods({
  'screenName': function() {
      T.get('search/tweets',
      {
        q:'#UCLA',
        count:1
      },
      function(err,data,response) {
        var temp = data.statuses[0].user.screen_name;
        console.log(temp);
        return temp;
      }
    )
  }
});

我使用Twitter的API和我想要做的基本上是从JSON检索屏幕名称,并将其返回给一个变量在客户端什么。但是,因为编译器已经达到了屏幕名功能结束后回调正在编译此函数返回不确定的。

I'm using the Twitter API and what I want to do is basically retrieve the screen name from the JSON and return it to a variable on the client side. But this is returning undefined because the callback is being compiled after the compiler has reached the end of the 'screenName' function.

我希望它从回调函数返回值,但读了其他的例子还没有帮我COM prehend我如何改变我的code。我需要这个功能,但同步的,我不知道该怎么办了。

I want it to return the value from the callback function but reading up other examples has not helped me comprehend how I can transform my code. I need to make this function synchronous but I don't know how to do it.

推荐答案

只需使用 Meteor.wrapAsync 把你的异步 T.get 成同步的风格之一!

Simply use Meteor.wrapAsync to turn your asynchronous T.get into a synchronously styled one!

这实际上并不会得到一个纯粹的同步的方式,虽然,它是利用被称为光纤的把戏执行,但你应该阅读文档,以了解更多信息。结果
这里所说:

It won't actually get executed in a pure "synchronous" way though, it is using a trick known as a Fiber, but you should read the docs to learn more.
Here goes:

var Tget = Meteor.wrapAsync(T.get);

Meteor.methods({
  'screenName': function() {
    return Tget({
      q : '#UCLA',
      count : 1
    }).status[0].user.screen_name;
  }
});

这篇关于让流星方法同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆