-1

i have a function insde a function and im trying to return somehthing wich i return in the inner function.

function calculatePoints(){
      request({
        success: onWiktionaryResponseAvailable,
        error: null,
        url: "https://en.wiktionary.org/w/api.php?action=query&origin=*&format=json&titles="+inputWord,
      });
      function onWiktionaryResponseAvailable(result){
        let wiktionaryEntry = JSON.parse(result),
          keys = Object.keys(wiktionaryEntry.query.pages);
          if (keys[0] === "-1"){
            return 0;
          }return inputWord.length;
      }
    }

i have tried to write: return onWiktionaryResponsAvailable(); but that doesn´t work in my case.

stoesselleon
  • 59
  • 1
  • 8
  • are you expecting `calculatePoints()` to be synchronous? If so, my first look at this is that what you're wanting to achieve is not possible – Dacre Denny Jun 17 '18 at 21:03

1 Answers1

0

You've already got the idea of a "callback" function here when you call your request. You just need to carry that one step further, and pass in a callback function. (You could also accomplish the same thing with a Promise)

function calculatePoints(callback) {
  request({
    success: onWiktionaryResponseAvailable,
    error: null,
    url: "https://en.wiktionary.org/w/api.php?action=query&origin=*&format=json&titles=" + inputWord,
  });
  function onWiktionaryResponseAvailable(result) {
    let wiktionaryEntry = JSON.parse(result),
      keys = Object.keys(wiktionaryEntry.query.pages);
    if (keys[0] === "-1") callback(0);
    callback(inputWord.length);
  }
}
David784
  • 7,031
  • 2
  • 22
  • 29
  • and how do i access this now ? do i have to give calculatePoints() a function within it ? . No im stuck with "callback is not a function" error – stoesselleon Jun 17 '18 at 21:13
  • The toughest part is to understand what it means to do something asynchronously. When you call `request`, you are **starting** a request. It could take a couple of milliseconds, or it could take a minute. So the code continues to execute, and when it succeeds it will call the `onWictionaryResponseAvailable`. Same thing with `calculatePoints`. It's wrapping an asynchronous function, so it's going to have to work the same way. – David784 Jun 17 '18 at 23:22