同步Meteor.methods函数内的MeteorJS异步代码 [英] MeteorJS async code inside synchronous Meteor.methods function

查看:88
本文介绍了同步Meteor.methods函数内的MeteorJS异步代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让客户端method.call等待异步函数完成?目前它到达函数的末尾并返回undefined。

How to get the client method.call to wait for an asynchronous function to finish? Currently it reaches the end of the function and returns undefined.

Client.js

Client.js

Meteor.call( 'openSession', sid, function( err, res ) {
    // Return undefined undefined
    console.log( err, res ); 
});

Server.js

Server.js

Meteor.methods({
    openSession: function( session_id ) {
        util.post('OpenSession', {session: session_id, reset: false }, function( err, res ){
            // return value here with callback?
            session_key = res;
        });
     }
});


推荐答案

Meteor的最新版本提供了无证件 Meteor._wrapAsync 函数将函数转换为标准(错误,res)回调到同步函数,意味着当前光纤在回调返回之前产生,然后使用Meteor.bindEnvironment确保保留当前的Meteor环境变量(例如 Meteor.userId())

Recent versions of Meteor have provided the undocumented Meteor._wrapAsync function which turns a function with a standard (err, res) callback into a synchronous function, meaning that the current Fiber yields until the callback returns, and then uses Meteor.bindEnvironment to ensure that you retain the current Meteor environment variables (such as Meteor.userId()).

一个简单的用法如下:

asyncFunc = function(arg1, arg2, callback) {
  // callback has the form function (err, res) {}

};

Meteor.methods({
  "callFunc": function() {
     syncFunc = Meteor._wrapAsync(asyncFunc);

     res = syncFunc("foo", "bar"); // Errors will be thrown     
  }
});

您可能还需要使用 function#bind 确保在包装之前使用正确的上下文调用 asyncFunc
有关详细信息,请参阅: https://www.eventedmind.com/tracks/feed -archive / meteor-meteor-wrapasync

You may also need to use function#bind to make sure that asyncFunc is called with the right context before wrapping it. For more information see: https://www.eventedmind.com/tracks/feed-archive/meteor-meteor-wrapasync

这篇关于同步Meteor.methods函数内的MeteorJS异步代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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