javascript - Meteor.call 不等待结果

标签 javascript meteor

Meteor.call 中的异步回调不会等待 Meteor.method 的结果。这是代码。

Meteor.call("fetchData",function (err,res) {
        if (err){
            console.log("error ", err);
        }else {
            console.log("success ", res);
            return res;
        }
    });//calling this from onRendered of client/somejs.js 

方法如下

fetchData :function(){
        HTTP.call("POST","http://localhost:8080",{
            data:'{"apple":"grape"}'
        },function (err,res) {
            if (err){
                console.log("error ", err);
            }else {
                console.log("success ", res);
                return res;
            }
        })
    }//Server/methods.js

当Meteor.call被触发时,我在服务器上得到一个成功的日志及其结果。 在客户端我得到 success undefined 。 客户端上的调用不会等待结果。我还尝试了服务器上的光纤和同步执行。它对我不起作用。在这种情况下,发布被阻止(我猜是由于 API 调用)。

另一件事是我尝试使用数据库查询而不是 API 调用进行相同的操作。效果很好。我从方法中得到了结果。

我哪里出错了。帮助。

谢谢

最佳答案

桑吉斯。

您的 future 之路是正确的。默认情况下,Meteor 的方法是异步的,因此客户端需要一些“等待”机制。为此,我建议使用 Meteor.wrapAsync 或 Promises。以下是关于实现两者的两个详细说明:

https://themeteorchef.com/snippets/synchronous-methods/#tmc-using-wrapasync

https://themeteorchef.com/snippets/promise-based-modules/#tmc-calling-our-promise-based-module-from-the-client

第二个链接更侧重于使用 Promise 构建代码,但提供了一个很好的演示,说明如何调用依赖于 Promise 响应的方法。

关于javascript - Meteor.call 不等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085253/

相关文章:

javascript - html Canvas 未填充颜色

javascript - React 无法渲染状态属性

javascript - 两个 div 同一类,仅获取该 div 的标题

javascript - 确保导入的 JavaScript 文件在切换路由后仍能正常工作

javascript - Meteor 中的 Google Analytics 与 Iron Router

python - 无法使用 Pymongo 连接到 Meteor

Javascript 字符 (ASCII) 到十六进制

javascript - 动态加载 JavaScript 文件

javascript - 从 Chrome 开发工具访问变量(js 命名空间)

javascript - Meteor - 为路由器获取数据时页面刷新导致闪烁