0

I have a function, which contains a sub function. I need to return a variable from the sub function however I am not sure how (I am new to JS).

I also want to avoid using a global variable, as I have about 15 more functions similar to this.

It shows the error, x is not defined.

    return data.rr_vin
    ^

ReferenceError: data is not defined

I have tried declaring the variable as an attribute of the function, i.e. function.myvar, however I still get the same issue.

function find_num() { 

    fetch("somefile.json")
    .then(res => res.json())
    .then(data => {
        a = data.numdata.filter(el => el.Process==="Process1").map(o => o.Finish_Time);

        b = recent_time(a)

        data.x= Math.max(data.numdata.filter(el => el.Finish_Time===b).map(o => o.Shortnum));
        console.log(data.x)

        return data.x
    })
    return data.x
}

Ideally I want to call on the find_num() function to return x.

  • There are two problems above: 1. `find_num` **can't** return `data.x` because `data` doesn't exist yet as of when `find_num` returns. Promise callbacks are always called *asynchronously*. See [the first](https://stackoverflow.com/questions/14220321/) linked question's answers for details. 2. `data` isn't in scope where the error occurs because it's a parameter to the `then` callback, so it doesn't exist outside the `then` callback. See [the second](https://stackoverflow.com/questions/500431/) linked question's answers for more details. Happy coding! Don't worry, it starts to make sense. :-) – T.J. Crowder May 14 '19 at 08:27
  • @T.J.Crowder thank you for such a detailed response I appreciate the help! I am a little confused however, when I call on `find_num()` surely it would run that function and create `data` allowing it to be returned? –  May 14 '19 at 09:21
  • It *starts* the asynchronous process, but that process doesn't *complete* until after `find_num` returns. – T.J. Crowder May 14 '19 at 09:34
  • @T.J.Crowder ah okay that makes sense, is there anyway around this, i.e. some way to change the order in which process complete. Am I correct in thinking the `.then` is a promise that manages small tasks? –  May 14 '19 at 09:43
  • `then` is a *method* on a promise object. Promises are a way to observe the completion of asynchronous tasks. You can't make an asynchronous task synchronous, which is why `find_num` can't return the result. See the first linked question's answers for details, including what to do instead of having `find_num` return the result. – T.J. Crowder May 14 '19 at 09:45

0 Answers0