简体   繁体   English

meteor.call与未返回的回调

[英]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. 我正在使用Meteor调用,并带有对服务器上某个方法的回调,该方法通过bitly收缩bitly ,但是尽管此方法在服务器上运行,但在客户端上却得到未定义的响应。

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. 在Meteor方法中使用Promises时,这是一个常见的错误。

To make Meteor resolve a Promise and return result to a client you should return the Promise at the end of this method: 为了使Meteor解决Promise并将结果返回给客户,您应该在此方法的结尾处​​返回Promise:

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. 您不应该添加.catch() ,它将由Meteor自动添加。

Useful article to read: Using Promises and async/await in Meteor . 阅读有用的文章: 在Meteor中使用Promises和async / await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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