【发布时间】: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