【问题标题】:JavaScript: Why is this promise not returning a value?JavaScript:为什么这个 Promise 没有返回值?
【发布时间】:2021-01-11 19:50:33
【问题描述】:

我遇到了一个函数,该函数应该从 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 []
    })
}

非常感谢任何帮助或建议!

【问题讨论】:

  • 你的函数中没有return。您确实在承诺链回调中使用了return,但您永远不会返回由承诺链构建的承诺。
  • 小心resultItems.push(...items) 返回数组的新长度,而不是数组本身,因此return resultItems.push(...items) 将返回一个数字而不是您期望的数组。您应该在 then 块中添加 resultItems.push(...items);,在 catch 块之后添加 return resultItems;
  • 非常感谢@secan,这对我有用:)
  • 如果你要将你的函数标记为async,那么在你的promise上使用await,这样你就可以从函数本身返回最终值(这将成为async 函数)。如果不是,则从您的函数返回顶级承诺,并确保所有子承诺都正确链接并返回它们的承诺或数据。基本上,这段代码是一团糟,因为您混合了两种处理多个异步操作的方法,并且没有遵循任何一种的正确技术。

标签: javascript fetch es6-promise fetch-api


【解决方案1】:
fetch(fetchURL)

应该是

return fetch(fetchURL)

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 2020-03-13
    • 2019-03-15
    • 2013-03-25
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多