单击按钮时获取多个 API

Fetch multiple APIs if a button is clicked

我正在尝试从同一个 API 中获取多个 URL。我有一组带有趋势 gif 的 url,但是,我只想在用户单击搜索按钮时推送一个新的 URL(带有搜索到的 gif)。我是 JS 的新手所以如果代码中有什么不合理的地方请告诉我

HTML

<body>
    <form>
        <label for="search">Search</label>
        <input id="search" type="search">
        <button id="btnSearch">Go</button>
    </form>
</body>

JS

function getAllUrls(urls) {
    try {
        let data = Promise.all(
            urls.map(url => fetch(url)
                .then(response => response.json())
                .then(content => {
                    console.log('[+]', content.data)
                    console.log('[-]', content.meta)
                })
            )
        )
        return data
    } catch (e) { console.log(e) };
}

function init() {
    let apiKey = 'xxxx';
    let urls = [
        `https://api.giphy.com/v1/gifs/trending?api_key=${apiKey}&limit=20&offset=3`,
    ]

    document.getElementById('btnSearch').onclick = function() {
        let userInput = document.getElementById('search').value.trim()
        let searchUrl = `https://api.giphy.com/v1/gifs/search?q=${userInput}api_key=${apiKey}&limit=20&offset=5`
        return urls.push(searchUrl)
    }

    let responses = getAllUrls(urls)
}

init()

问题: 基本上,获取功能仅 returns 趋势 gif 的数据。我的意思是,即使我点击了搜索按钮,该功能也只会检索热门 gif

该按钮将提交表单并因此刷新页面。尝试设置为键入按钮或阻止默认操作。

<button id="btnSearch" type="button">Go</button>
<!-- or prevent default form submission -->

另外,您似乎也没有在等待 Promise.all(),returns 一个承诺。尝试将该函数重构为:

function getAllUrls(urls) {
  return Promise.all(urls.map(url => fetch(url))).then(async (res) => {
    const data = await Promise.all(res.map(r => r.json()))
    data.forEach(d => {
      console.log('[+]', content.data)
      console.log('[-]', content.meta)
    })
    return data
  })
}

尝试在按钮单击事件中移动 getAllURLs 函数:

function init() {
  let apiKey = 'xxxx';
  let urls = [`https://api.giphy.com/v1/gifs/trending?api_key=${apiKey}&limit=20&offset=3`]

  document.getElementById('btnSearch').onclick = async function() {
      let userInput = document.getElementById('search').value.trim()
      let searchUrl = `https://api.giphy.com/v1/gifs/search?q=${userInput}api_key=${apiKey}&limit=20&offset=5`
      urls.push(searchUrl)
      const responses = await getAllUrls(urls)
  }
}