我怎样才能等待获取结果?

时间:2021-05-19 16:57:47

标签: javascript asynchronous promise fetch

我正在提供获取 API 的第一步,但我肯定遗漏了一些东西。

我想要一个接受查询作为参数并从 API 获取数据的函数:

const fetchImgs = (query) => {
  fetch(`http://www.splashbase.co/api/v1/images/search?query=${query}`)
    .then((response) => response.json())
    .then((data) => data.images)
    .catch((err) => {
      displayAlert(err)
    })
}

然后我想对收到的数据做一些事情。例如,在窗口加载时,我想用森林图像填充轮播,或者当我单击按钮时,我想用海滩图像填充相册。像这样:

window.onload = () => {
  const forestsArray = fetchImgs("forest")
  populateCarousel(forestsArray)
}

mainImgBtn.addEventListener("click", () => {
  const beachesArray = fetchImgs("beaches")
  populateAlbum(beachesArray)
})

我知道我可以在每次需要时获取我的图像,并且在第二个 then 中我可以调用函数来填充内容,但我很好奇是否有任何方法(如果它确实有意义)使我的 fetchImgs() 函数可重用。因为问题在于,当我调用 populate 函数时,我仍然无法访问来自 fetchImgs() 的数据,而且我无法执行 fetchImgs().then(something),因为 fetchImgs() 没有t 返回承诺。

我也知道我可以将 populate 函数包装在 setTimeout 上,但我认为这有点脏。有没有更好的办法?

0 个答案:

没有答案