1

I have a function called wikiCount that I'm using to wrap another function from an API like this:

 var wikiCount = function(wikiPage, word){

      wtf_wikipedia.from_api("Toronto", "en", function(markup){

        var obj = wtf_wikipedia.plaintext(markup)
        var a = obj.toLowerCase().split(" ").count(word)
        return a

    })
}

How can I return a value from the nested API function so that I can use it in the wrapper function. The whole purpose of doing this is because I'm trying to access the variable "a" outside the function.

ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • What is the API? They probably have documentation or example code that would help with this. – 4castle May 09 '16 at 21:18
  • 2
    There are answers to this question here: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 4castle May 09 '16 at 21:22

1 Answers1

0

A cool way is with promises:

var Promise = require('bluebird');

function wikiCount(wikiPage, word){

     return new Promise(function(resolve, reject) {

        wtf_wikipedia.from_api("Toronto", "en", function(markup){

            var obj = wtf_wikipedia.plaintext(markup)
            var a = obj.toLowerCase().split(" ").count(word)

            resolve(a);

        });
    });
}

wikiCount('somePage', 'someWord')
.then(function(result) {
  // do something with the result
  // this is 'a' that you resolved in the function above
});

The above example uses the bluebird promise library. If you're in a browser or a Node.js runtime that supports ES6, you can use native Promises.

The above is referred to as "Promisification":

Promisification means converting an existing promise-unaware API to a promise-returning API.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68