在客户端上从 Meteor.call 获取未定义,但在服务器上变量包含数据

Getting undefined from Meteor.call on client, but on server variable contains data

本文关键字:服务器 包含 数据 变量 获取 客户端 Meteor call 未定义      更新时间:2023-09-26

我在服务器上有一个这样的函数

Meteor.methods({
"functionName": function(data) {
//calculations, http requests etc.
console.log(variable); //shows variable properly
return variable;
}
});

当我在服务器上console.log(variable)时,我可以看到数据。

现在我在客户端上做Meteor.call

Meteor.call('functionName', data, function(err, res) {
console.log(res); //shows undefined
});

这是怎么回事?为什么我不能在客户端上使用响应变量?

编辑:

我已经为此苦苦挣扎了几个小时,我将错误范围缩小到一个HTTP.get()功能。现在它看起来像这样:

//some calculations
var variable = HTTP.get('url');
return variable.data; //should return an object

我试图用承诺包裹它,但后来它不起作用。它看起来像这样:

//some calculations
function promise() {
  var variable = HTTP.get('url');
  resolve('Done.');
}
promise().then(function() {
  console.log(variable); //doesn't even work on server this way
  return variable;
});

根据评论和您的问题,我的猜测是您的 return 语句发生在 HTTP 请求的异步回调中。 您可以使用 Meteor.wrapAsync 或 Promise 使这些请求同步并获取有效的返回语句。

由于同步调用 http 而发生此问题。这里真正发生的事情不是等待 http 调用响应。你应该使用Meteor.wrapAsync;

相关文章: