2017-06-10 10 views
-1

私はES6 Javascriptの初心者ですが、fetch()を使用してFourSquare APIからデータを取得し、結果をいくつかのリスト項目に貼り付けるモジュールを作成しようとしています。Fetch API - 返された変数undefined

モジュールのコードは以下の通りです:

export default (config) => class fourSquare { 

constructor(){ 
    this.clientid = config.client_id; 
    this.secret = config.client_secret; 
    this.version = config.version; 
    this.mode = config.mode; 
} 

getVenuesNear (location) { 
    const apiURL = `https://api.foursquare.com/v2/venues/search?near=${location}&client_id=${this.clientid}&client_secret=${this.secret}&v=${this.version}&m=${this.mode}`; 

    fetch(apiURL) 
     .then((response) => response.json()) 
     .then(function(data) { 
      const venues = data.response.venues; 


      const venuesArray = venues.map((venue) =>{ 
       return { 
        name: venue.name, 
        address: venue.location.formattedAddress, 
        category: venue.categories[0].name 
       } 
      }); 


      const venueListItems = venuesArray.map(venue => { 
       return ` 
        <li> 
         <h2>${venue.name}</h2> 
         <h3>${venue.category}</h3> 
        </li> 
       `; 
      }).join(''); 

      return venueListItems; 


     }) 
    .catch(function(error) { 
     //console.log(error); 
    }); 
} 

}

私は別のファイルにこのモジュールをインポートすると、返されたリスト項目を使用しようとしています:

const venueHTML = fourSquareInstance.getVenuesNear(locationSearchBox.value); 

    console.log(venueHTML); 

しかし、結果は常に未定義です。私が変更した場合:return venueListItemsからconsole.log(venueListItems)にリストアイテムがコンソールに記録されるので、モジュール内のコードはOKです。私はこれがfetch()の非同期の性質のためかもしれないが、getVenuesNear関数からデータを返すように私のコードを再因子付けする方法がわからないと思う。あなたがfetch()の結果を返す必要が

答えて

3

:あなたはgetVenuesNear関数を呼び出すとき

return fetch(apiURL) 

はまた、あなたが結果にアクセスするためにthenメソッドを使用する必要があります。

fourSquareInstance.getVenuesNear(locationSearchBox.value).then(venueHTML => { 
    console.log(venueHTML); 
});