简体   繁体   中英

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;
         });
  }
});

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM