简体   繁体   English

使 Meteor 方法同步

[英]Make Meteor method synchronous

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.我已经阅读了几篇关于 Async 的 Stack Overflow 帖子,但我无法理解我如何能够使其同步。 As of now, it is asynchronous therefore it returns undefined before heading into the callback function.到目前为止,它是异步的,因此它在进入回调函数之前返回 undefined 。

I call it from the client side:我从客户端调用它:

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;
      }
    )
  }
});

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.我正在使用 Twitter API,我想要做的基本上是从 JSON 中检索屏幕名称并将其返回给客户端的变量。 But this is returning undefined because the callback is being compiled after the compiler has reached the end of the 'screenName' function.但这将返回 undefined ,因为在编译器到达 'screenName' 函数的末尾之后正在编译回调。

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.我需要使这个函数同步,但我不知道该怎么做。

Simply use Meteor.wrapAsync to turn your asynchronous T.get into a synchronously styled one!只需使用Meteor.wrapAsync将您的异步T.get变成同步样式的!

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.它实际上不会以纯粹的“同步”方式执行,它使用了一种称为 Fiber 的技巧,但您应该阅读文档以了解更多信息。
Here goes:开始:

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

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

Browser-to-server, it is not possible to call methods synchronously .浏览器到服务器,不可能同步调用方法 You're stuck with callback-style code.你被回调风格的代码困住了。 Synchronous calls are only possible on the server.同步调用只能在服务器上进行。

http://docs.meteor.com/#/basic/Meteor-call http://docs.meteor.com/#/basic/Meteor-call

On the client在客户端

Methods called on the client run asynchronously, so you need to pass a callback in order to observe the result of the call.客户端调用的方法是异步运行的,所以你需要传递一个回调来观察调用的结果。 The callback will be called with two arguments, error and result.将使用两个参数调用回调,错误和结果。 The error argument will be null unless an exception was thrown.除非抛出异常,否则错误参数将为空。 When an exception is thrown, the error argument is a Meteor.Error instance and the result argument is undefined.当抛出异常时,错误参数是一个 Meteor.Error 实例,结果参数是未定义的。

On the server在服务器上

On the server, you don't have to pass a callback — the method call will simply block until the method is complete, returning a result or throwing an exception, just as if you called the function directly.在服务器上,您不必传递回调——方法调用将简单地阻塞,直到方法完成,返回结果或抛出异常,就像您直接调用函数一样。

However, synchronous style code for the server depends if everything else is synchronous.但是,服务器的同步样式代码取决于其他所有内容是否同步。 You might want to read the APIs docs if it is possible to write the Twitter API call synchronously.如果可以同步编写 Twitter API 调用,您可能需要阅读 API 文档。 Otherwise, you'll be writing asynchronous code in the end.否则,您最终将编写异步代码。

@thatgibbyguy answer is the only one that worked for me. @thatgibbyguy 的答案是唯一对我有用的答案。 I also tried following libraries (maybe they will be useful for somebody):我还尝试了以下库(也许它们对某些人有用):

meteor add simple:reactive-method
meteor add mnmtanish:call

I use the Promisse, is a great response with async/await.我使用了 Promise,是一个很好的 async/await 响应。

Example:例子:

// On Client

Template.nameTemplate.onCreated(async function(){
    const callFunctionTest = await getScoreByCountry({ name: 'Testando' });
    console.log(callFunctionTest);

});


async function getScoreByCountry(filter) {
    return await new Promise((resolve, reject) => {
        Meteor.call('app-method-test', filter , (error, resp) => {
            if(error) {
                reject(error)
            } else {
                resolve(resp)
            }
          })
    })
}


// On server

Meteor.methods({
    'app-method-test': test 
});

function test(filter = {}) {
    return App.Collections.NameCollection.findOne(filter)
}

This isn't synchronous code, but what I've done to send a server method's result back to a client side function is used serversession to do this.这不是同步代码,但我所做的将服务器方法的结果发送回客户端函数是使用serversession来执行此操作的。 For example:例如:

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

You can now set a reactiveVariable, or a session, or a template helper to be:你现在可以将一个reactiveVariable、一个会话或一个模板助手设置为:

ServerSession.get('screenname')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM