【问题标题】:Meteor.call does not wait for the resultMeteor.call 不等待结果
【发布时间】:2017-04-26 09:33:18
【问题描述】:

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 的形式记录其结果。 在客户端我得到 success undefined 。 客户端上的调用不等待结果。我还尝试在服务器上执行 Fibers 和同步执行。它对我不起作用。在这种情况下,发布被阻止(我猜是由于 API 调用)。

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

我哪里出错了。求助。

谢谢

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    桑吉斯。

    你在未来的道路上是正确的。默认情况下,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 响应的方法。

    【讨论】:

    • 但是为什么在数据库查询的情况下同样有效。我有一个方法可以检查用户名是否已经存在。这工作正常,我在客户端的 Meteor.call 上收到了结果。顺便说一句,我会检查链接。我对 JS 很陌生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多