我试图从相同的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()
问题:基本上,fetch函数只返回趋势gif的数据。我的意思是,即使我点击了搜索按钮,这个功能也只能检索趋势gif
按钮将填充表单并刷新页面。尝试设置键入按钮或阻止默认操作。
<button id="btnSearch" type="button">Go</button>
<!-- or prevent default form submission -->
也似乎你不是等待返回承诺的Promise.all()
。试着这样重构这个函数:
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)
}
}