1

I have a function that uses lodash's .find method to return the value (IATA code) of an object that matches the variable (location). I need to be able to call on this function to push the IATA code into a DB from just the location, however I think it's currently out of scope and I can't work out how to get the results to return properly.

Any pointers would be greatly appreciated.

Function

var newCode = function getIATA () {

  jsonfile.readFile(file, function(err, obj) {

    // This works
    console.log('1.' + ' ' + location)

    var iataCode = _.result(_.find(obj, function (obj1) {
      return obj1.name === location
    }), 'iata')

    // This works as well
    console.log('2.' + ' ' + iataCode)
  })
}

// This does not

newCode(location);
console.log('3.' + ' ' + newCode)

Console.log (It comes in this order, so I'm assuming that's wrong

3. function getIATA() {

      jsonfile.readFile(file, function(err, obj) {
        // This works
        console.log('1.' + ' ' + location)

        var iataCode = _.result(_.find(obj, function (obj1) {
          return obj1.name === location
        }), 'iata')
        // This works as well
        console.log('2.' + ' ' + iataCode)
      })
    }
POST /add 302 36.253 ms - 46
1. City
2. LCY
Rhys Edwards
  • 771
  • 2
  • 14
  • 32

1 Answers1

0

This is just the nature of asynchronous behavior. It is out of order, in a sense.

Reading the json file takes some n amount of milliseconds and then executes its code, resulting in that section showing after the initial execution of the main code segment.

Travis J
  • 81,153
  • 41
  • 202
  • 273