0

How can I get the 'return' value from alexa function?

I tried making a new function init() to wrap all the operation, but no luck. Not even error or something, and when I use

console.log(result.rank);

I receive the correct value in the console, without problems.

3

Code

rank: function() {
    var a = document.createElement('a');
    a.href = this.url;
    var alexa = require('alexarank');
    function init(){
    alexa(a.hostname, function(error, result) {
        if (!error) {
          return result.rank;
        } else {
            console.log(error);
        }
      });
    }
    return init();
Isaac
  • 160
  • 1
  • 1
  • 8

2 Answers2

0

Easiest thing to do in a Meteor method is to use Meteor.wrapAsync:

rank: function() {
    var alexa = require('alexarank');
    var alexaSync = Meteor.wrapAsync(alexa);
    var result = alexaSync(a.hostname);
    return result.rank;
}

Meteor.wrapAsync takes an asynchronous function which accepts a callback as it's last argument and makes it work as though it was synchronous (through the magic of Fibers)


Note that Meteor methods can also return promises and will wait for the promise to resolve. So if the library you are using supports promises you can make your function an async function and await the result from the library. Or wrap it's callback in your own promise and await/return that.

coagmano
  • 5,542
  • 1
  • 28
  • 41
0

I managed to do it, passing a callback: https://stackoverflow.com/a/6847754/7693078

rank: function() {
    var a = document.createElement('a');
    a.href = this.url;
    var alexa = require('alexarank');
    function ranking(x,y){ 
      alexa(a.hostname, function(error, result) {
        if (!error) {
           y(result.rank);
        } else {
           console.log(error);
        }
      });
    }
    ranking("x", function(y){
      var span = document.getElementById("ranking");
      var txt = document.createTextNode(y);
      span.appendChild(txt);
    });
  }
Isaac
  • 160
  • 1
  • 1
  • 8
  • If this is a meteor method, it will run on the server where there is no document to create elements with... – coagmano Apr 12 '18 at 06:57