2015-11-20 45 views
0

我从流星中的wrapAsync函数获取返回值时遇到了问题。以下是我的代码流星从异步函数中获取值

Template.greet.helpers({ 
    greet : function() { 
    var convertAsyncToSync = Meteor.wrapAsync(HTTP.get); 
    resultOfAsyncToSync = convertAsyncToSync('http://www.demo.com/api/greet', {}); 
    console.log(resultOfAsyncToSync); 
    return resultOfAsyncToSync; 
    } 
}); 

我在控制台中得到未定义的值。

+0

使用reactiveDict或reactiveVar保存值 – Sasikanth

+0

感谢您的答复。我尝试了下面的代码,但我仍然无法从中得到任何东西。 Template.greet.helpers({ 的greet:函数(){ VAR convertAsyncToSync = Meteor.wrapAsync(HTTP.get); resultOfAsyncToSync = convertAsyncToSync( 'http://www.demo.com/api/greet',功能(错误,响应){ alert('response'); console.log(response); return response.data; }); } }); 现在我的反应被打印在控制台中,但没有任何返回模板 – Subhash

回答

0

尝试

Template.greet.onCreated(function(){ 
    this.apiResult = new ReactiveVar(null); 
}) 
Template.greet.helpers({ 
    greet : function() { 
    var t = Template.instance(); 
    HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){ 
     //process response and save it in reactivevar 
     t.apiResult.set(r.data); 
    }); 
    return t.apiResult.get(); 
    } 
}); 

不要忘记补充包meteor add reactive-var

编辑

Template.greet.onRendered(function(){ 
    var t = Template.instance(); 
    HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){ 
    //process response and save it in reactivevar 
    t.apiResult.set(r.data); 
    }); 
}) 

Template.greet.helpers({ 
    greet : function() { 
    var t = Template.instance(); 
    return t.apiResult.get(); 
    } 
}); 
+0

谢谢。有效! – Subhash

+0

自从我的控制台充满日志后,它是否会多次调用HTTP.get函数。 这是我的日志显示: Firebug的日志限制已经达到。未显示1290个条目。 – Subhash

+0

这取决于你打电话给帮手的次数是多少次 – Sasikanth