Fetch API - 返回的变量未定义
Fetch API - returned variable undefined
我是 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);
});
}
}
我正在将此模块导入另一个文件并尝试使用 returned 列表项:
const venueHTML = fourSquareInstance.getVenuesNear(locationSearchBox.value);
console.log(venueHTML);
但结果总是不确定的。我知道模块中的代码是可以的,因为如果我更改: return venueListItems
到 console.log(venueListItems)
列表项将记录到控制台。我相信这可能是由于 fetch() 的异步性质,但不确定如何将我的代码重构为来自 getVenuesNear 函数的 return 数据。
您必须 return fetch()
的结果:
return fetch(apiURL)
另外,当你调用getVenuesNear
函数时,你必须使用then
方法来访问结果:
fourSquareInstance.getVenuesNear(locationSearchBox.value).then(venueHTML => {
console.log(venueHTML);
});
我是 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);
});
}
}
我正在将此模块导入另一个文件并尝试使用 returned 列表项:
const venueHTML = fourSquareInstance.getVenuesNear(locationSearchBox.value);
console.log(venueHTML);
但结果总是不确定的。我知道模块中的代码是可以的,因为如果我更改: return venueListItems
到 console.log(venueListItems)
列表项将记录到控制台。我相信这可能是由于 fetch() 的异步性质,但不确定如何将我的代码重构为来自 getVenuesNear 函数的 return 数据。
您必须 return fetch()
的结果:
return fetch(apiURL)
另外,当你调用getVenuesNear
函数时,你必须使用then
方法来访问结果:
fourSquareInstance.getVenuesNear(locationSearchBox.value).then(venueHTML => {
console.log(venueHTML);
});