2016-12-16 188 views
1

我有一個函數,它使用lodash.find方法返回與變量(位置)匹配的對象的值(IATA代碼)。我需要能夠調用這個函數來將IATA代碼從該位置推送到數據庫中,但是我認爲它現在超出了範圍,我無法弄清楚如何讓結果正確返回。從函數返回結果

任何指針將不勝感激。

功能

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(它有這個順序,所以我假設是錯誤的

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 
+1

你的newCode函數不帶任何參數。 – Majid

回答

0

這是異步行爲只是性質。它在某種意義上,它是無序的。

讀取json文件需要一些n密爾liseconds ,然後執行其代碼,導致該部分顯示在主代碼段的初始執行之後。