javascript - 添加异步等待以获取 javascript
问题描述
我是异步和等待的新手。我正在使用 api 和 fetch 在食谱网站上工作。需要帮助将异步等待添加到 fetch。我正在使用spoonacular api。没有错误只是想添加异步等待。
function retrieve(e) {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
data.results.forEach((results) => {
let li = document.createElement("li");
let a = document.createElement("a");
let div = document.createElement("div");
let img = document.createElement("img");
let btn = document.createElement("button");
// styling
div.className = "newsdiv";
img.className = "newsimg";
btn.className = "btns";
li.style.width = "300px";
a.setAttribute("href", results.sourceUrl);
a.setAttribute("target", "_blank");
img.setAttribute("src", results.image);
div.textContent = results.title;
// btn.prepend(br);
div.appendChild(a);
div.prepend(img);
li.prepend(div);
btn.textContent = "Get Recipe";
div.appendChild(btn);
a.appendChild(btn);
newsList.appendChild(li);
});
})
.catch((error) => {
console.log(error);
});
}
解决方案
看下面的片段。这对您的解决方案很有用。在函数中,你可以做任何你想做的操作。
const retrieve = async (e) => {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
const response = await fetch(url);
const myJson = await response.json(); //extract JSON from the http response
console.log(myjson);
}
retrieve(null);
推荐阅读
- python - 在 Python 中将数据附加到文件
- c++ - 为什么 Visual Studio 正在摆脱我的反斜杠字符串
- python - 为什么每次打开 Jupyter Notebook 时都必须在 Anaconda 中重新安装 scikit learn?
- java - 实现一个将覆盖 onClick() 的类
- jq - jq在文本值具有引号文字时使用包含方法
- c - 在 C 中设置二维字符数组时出现 SegFault
- php - get_post_meta()不显示wordpress循环中第一项的字段值
- android - 无法在华为设备中显示通知
- flutter - 升级到 macOS Catalina 后将颤振路径从 .bash_profile 更改为 .zprofile
- python - 如何从最后一个“。”之后的字符串中删除最后一个字符