Fetch API - returned variable undefined

2019-08-21 08:39发布

问题:

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