return values from server side meteor methods

2019-09-19 03:40发布

问题:

Here is my code,

googleContacts:function()
        {

            var opts= { email: Meteor.user().services.google.email,
              consumerKey: "xxxxxxxx",
              consumerSecret: "xxxxxxxxxx",
              token: Meteor.user().services.google.accessToken,
              refreshToken: Meteor.user().services.google.refreshToken};

            gcontacts = new GoogleContacts(opts);

            gcontacts.refreshAccessToken(opts.refreshToken, function (err, accessToken)
             {
                if(err)
                {
                    console.log ('gcontact.refreshToken, ', err);
                    return false;
                }
                else
                {
                    console.log ('gcontact.access token success!');
                    gcontacts.token = accessToken;
                    gcontacts.getContacts(function(err, contact) 
                    {
                      console.log(contact);
                       return contact;//want to return this value
                    })

                }
             });

        }

I want to return the contact to the called method,as it is in a inner function i'm getting a bit difficult to return it to the called method.If it is in client side,then we can store the value in a session variable and we can return that,but this is a server side method,How to do this?

回答1:

Use Futures:

Future = Npm.require('fibers/future');

Meteor.methods({

  methodname: function() {
    var fut = new Future();
    apiCall(function(err, res) {
      fut.return(...);
    });
    return fut.wait();
  },

});