如何解决JavaScript:为什么这个承诺没有返回值?
我迷上了一个应该从API提取数据然后返回预定义类型数组的函数。但是,我总是会收到一条错误消息,指出A function whose declared type is neither 'void' nor 'any' must return a value.
我真的不明白为什么会显示此消息,因为我的函数中有一个返回语句,即使在获取数据时发生错误:
export async function queryOpenCage(query: string): Promise<MarkerPoint[]> {
const {opencageApiKey}: ClientSettings = JSON.parse(
document.getElementById(ElementID.Settings)!.textContent!
)
const fetchURL = `https://api.opencagedata.com/geocode/v1/json?key=${opencageApiKey}&q=${query}&limit=5&pretty=1`
const resultItems: MarkerPoint[] = []
fetch(fetchURL)
.then(response => {
return response.json()
})
.then(json => {
const items = json.results.map((res: any) => {
return {
lat: res.geometry.lat,lng: res.geometry.lng,address: res.formatted
}
})
return resultItems.push(...items)
})
.catch(error => {
return []
})
}
任何帮助或建议都将受到高度赞赏!
解决方法
fetch(fetchURL)
应该是
return fetch(fetchURL)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。