如何从 Meteor 自己的回调调用异步方法? [英] How to call async method from Meteor own callbacks?

查看:53
本文介绍了如何从 Meteor 自己的回调调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚花了几个小时阅读了诸如 Meteor:在 Meteor.method 中调用异步函数并返回结果

I've just spent a few hours reading SO with answers such as Meteor: Calling an asynchronous function inside a Meteor.method and returning the result

不幸的是,我仍然没有设法使用光纤或期货.

Unfortunately, I still didn't manage to user fibers, or futures for that matter.

我正在尝试做一些相当简单的事情(我认为!).

I'm trying to do something fairly simple (I think!).

创建用户时,根据异步方法的结果,向用户对象添加变量.所以想象一下,如果你会在名为 BANK 的 3rd 方数据库服务器上调用我的异步方法,这可能需要几秒钟才能返回.

When creating a user, add a variable to the user object, based on the result of an asynchronous method. So imagine if you will my async method is called on a 3rd party db server called BANK, which could take several seconds to return.

Accounts.onCreateUser(function(options,user){

var Fiber = Npm.require("fibers");

Fiber(function() { 
    BANK.getBalance(function(err, theBalance) {

        if (err) return console.log(err);

        _.extend(user,{
            balance: theBalance;
        });

    });
}).run();

return user;

});

所以上面发生的事情是调用了 BANK 方法,但是当它返回时,代码已经移动了并且 _.extend 从未被调用.

So what happens in the above is that the BANK method is called, but by the time it returns the code has already moved on and _.extend is never invoked.

我尝试将返回调用放置在 Fiber 中,这只会让事情变得更糟:它永远不会返回用户.嗯,确实如此,但为时已晚 3 秒,所以到那时下游的一切都在纾困.

I tried placing the return call inside the Fiber, that only made things worse: it never return user. Well it did, but 3 seconds too late so by then everything downstream was bailing out.

感谢您的帮助!

推荐答案

回答我自己的问题,希望将来能帮助到一些人.这是基于 Avital Oliver 和 David Glasser 的出色建议,他们可以查看 Mike Bannister 的meteor-async.md.你可以在这里阅读:https://gist.github.com/possibilities/3443021>

Answering my own question which hopefully will help some people in the future. This is based on the excellent advice of Avital Oliver and David Glasser to have a look at Mike Bannister's meteor-async.md. You can read it here: https://gist.github.com/possibilities/3443021

Accounts.onCreateUser(function(options,user){
    _.extend(user,{
        balance: getBalance(),
    });
  return user;
});


function getBalance() {
  var Future = Npm.require("fibers/future");
  var fut = new Future();
  BANK.getBalance(function(err, bal) {
    if (err) return console.log(err);
    fut.return(bal);
  });
  return fut.wait();
}

我相信有一种更好的方法来处理这个问题,直接将 BANK API 包装在 npm 包本身中的 Futures 中,根据这个例子(来自 Avital Oliver):https://github.com/avital/meteor-xml2js-npm-demo/blob/master/xml2js-demo.js

I believe there's an even better way to handle this, which is directly by wrapping the BANK API in Futures within the npm package itself, as per this example (from Avital Oliver): https://github.com/avital/meteor-xml2js-npm-demo/blob/master/xml2js-demo.js

希望能帮到你!

这篇关于如何从 Meteor 自己的回调调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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