Nick Wild
Nick Wild

Reputation: 575

meteor.call with callback returning undefined

I appreciate that there are many questions on this but I can't seem to find a relevant answer.

I am using a Meteor call with a callback to a method on the server that shrinks an URL via bitly, but although this runs on the server, I am getting a undefined response back on the client.

Any ideas here is the code?

Client

Meteor.call('bitlyShrink','http://test.com', function(error, response) {
  console.log(error);
  console.log(response);
})

Server

Meteor.methods({
  bitlyShrink(longurl) {
    check (longurl, String);

    const BitlyClient = require('bitly'),
          bitly = BitlyClient('token');

    bitly.shorten( longurl )
         .then( function ( response ) {
           console.log(response);
           return response;
         })
         .catch( (error ) => {
           return error;
         });
  }
});

Upvotes: 0

Views: 162

Answers (1)

Styx
Styx

Reputation: 10076

That's a common mistake made while using Promises in Meteor methods.

To make Meteor resolve a Promise and return result to a client you should return the Promise at the end of this method:

Meteor.methods({
  bitlyShrink(longurl) {
    check (longurl, String);

    const BitlyClient = require('bitly'),
          bitly = BitlyClient('token');

    const bitlyPromise = bitly.shorten(longurl);
    // do something else, if needed
    return bitlyPromise;
  }
});

You should not add .catch(), it will be added by Meteor automatically.

Useful article to read: Using Promises and async/await in Meteor.

Upvotes: 2

Related Questions