Meteor method not returning error or result value

前端 未结 2 1581
清酒与你
清酒与你 2021-01-28 07:28

Here is my server side code

Meteor.methods({
   addSupportRequest: function (support) {
    Support.insert(support, function (err, id) {
        if (err)
                


        
相关标签:
2条回答
  • 2021-01-28 08:08

    Dsyko's answer was somewhat on the right track. However, the asynchronous callback will never pass its result to the scope of the original function, which has ended.

    What you want is to run the Support.insert operation synchronously, i.e. having the current fiber yield while I/O is happening. This is what the Meteor._wrapAsync function is for. Luckily for you, there is no need to do this manually because if you just take out the callback from the insert operation, it will run synchronously:

    Meteor.methods({
       addSupportRequest: function (support) {
         var id = Support.insert(support);
         // An error may be thrown here, but it certainly won't be a network error because the request will have already reached the server.
         console.log("Support request added: " + id);
         return id;
       });
    }
    
    0 讨论(0)
  • 2021-01-28 08:12

    One issue that is preventing your method from returning a result is that return id; is in the function scope of the insert callback, and not the scope of the meteor method. So it will return from the callback and then there is no return in the meteor method function which is implicitly a return undefined.

    You should add a return to the method's scope like this:

    Meteor.methods({
       addSupportRequest: function (support) {
        return Support.insert(support, function (err, id) {
            if (err)
                throw new Meteor.Error(404, "Oops! Network Error. Please submit help request again. ");
    
                console.log("Support resuest added: " + id);
               return id;
    
        });
    } // End addSupportRequest
    

    As for the error, I am not sure why it isn't surfacing as it should traverse up the call stack (doesn't matter that it is inside an inner function like the return) and since it is a Meteor.Error it should get sent to the client as well.

    0 讨论(0)
提交回复
热议问题