获取API - 返回的变量未定义

时间:2017-06-10 17:00:30

标签: javascript ecmascript-6 es6-promise fetch-api

我是ES6 Javascript的新手,并且一直在尝试编写一个模块,使用fetch()从FourSquare API中获取一些数据,并将结果粘贴到一些列表项中。

该模块的代码如下:

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),列表项将记录到控制台。我相信这可能是由于fetch()的异步性质,但不确定如何重新调整我的代码以从getVenuesNear函数返回数据。

1 个答案:

答案 0 :(得分:3)

您必须返回fetch()的结果:

return fetch(apiURL)

此外,当您调用getVenuesNear函数时,您必须使用then方法来访问结果:

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