【问题标题】:Fetch API - returned variable undefinedFetch API - 返回的变量未定义
【发布时间】:2017-11-12 12:56:00
【问题描述】:

我是 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 函数返回数据。

【问题讨论】:

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


    【解决方案1】:

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

    return fetch(apiURL)
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2019-10-13
      • 2020-08-21
      • 2012-01-16
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多