首页 > 解决方案 > 添加异步等待以获取 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);
    });
  }

标签: javascript

解决方案


看下面的片段。这对您的解决方案很有用。在函数中,你可以做任何你想做的操作。

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);


推荐阅读