Fetch API - returned variable undefined

随声附和 提交于 2019-12-12 06:48:25

问题


I am a bit of a newbie to ES6 Javascript and have been trying to write a module to grab some data from the FourSquare API using fetch() and stick the results into some list items.

The code for the module is below:

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);
    });
}

}

I am importing this module in another file and attempting to use the returned list items:

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

    console.log(venueHTML);

But the result is always undefined. I know that the code within the module is OK because if I change: return venueListItems to console.log(venueListItems) the list items are logged to the console. I believe this may be due to the asynchronous nature of fetch() but not sure how to re-factor my code to return data from the getVenuesNear function.


回答1:


You have to return the result of fetch():

return fetch(apiURL)

Also, when you call the getVenuesNear function, you have to use the then method to access the result:

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


来源:https://stackoverflow.com/questions/44475873/fetch-api-returned-variable-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!