я хочу вызвать две функции одним щелчком мыши и убедиться, что они будут работать одна за другой - PullRequest
0 голосов
/ 24 марта 2020

Я хотел бы получить помощь в решении проблемы, которую я пытаюсь решить, поэтому проблема в том, что мне нужно вызвать два URL-адреса API. второе зависит от первого (в первой выборке я получаю некоторую базовую информацию, включая идентификаторы, во второй выборке я хочу получить данные на основе идентификаторов из первой выборки). я всегда получаю эту ошибку: Uncaught TypeError: Cannot read property 'length' of undefined, вероятно, мой подход не верен. я пробовал несколько вещей, таких как помещение второй функции внутрь первой, я пытался сделать это без asyn c, она работает только тогда, когда у меня есть две разные кнопки. Я думаю, асин c вызывает эту проблему (пытается получить длину до ответа), пожалуйста, помогите мне с этим. Я хотел бы получить представление о подходе или любом способе его решения. заранее спасибо. это проблема c код

//recipies by ingredients array
var displayData = [];
//full recipies array
var displayRecipes = [];

document.getElementById("search").addEventListener("click", function () {
  var l = document.getElementsByClassName("ingInput").length
  var ing = document.getElementById('id').value
  var ing1 = ''
  //getting all the values from the inputs so i can search it in the api url
  for(var i = 1; i<l ;i++){
    ing1 += ',' + document.getElementsByClassName("ingInput")[i].value 
  }
  //async get request for the api url 
 async function postData(url = '') {
    const response = await fetch(url, {
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },

    });
    return response.json(); // parses JSON response into native JavaScript objects
  }
  //the api url with the inputs values for searching by ingredeints
  postData('https://api.spoonacular.com/recipes/findByIngredients?ingredients='+ ing + ing1 + '&number=10&apiKey=API_KEY')
    .then((data) => {
      displayData.push(data); // JSON data parsed by `response.json()` call
      console.log('done')
    });

})

//second func
document.getElementById("search").addEventListener("click", function () {
//trying to get data from this array, here i have error.
  var l = displayData[0].length
  var ids = []
  for(var i = 0; i<l ;i++){
    ids.push(displayData[0][i].id) 
  }

  async function postData(url = '') {
    // Default options are marked with *
    const response = await fetch(url, {
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },

    });
    return await response.json(); // parses JSON response into native JavaScript objects
  }

  postData('https://api.spoonacular.com/recipes/informationBulk?ids='+ids.toString()+'&apiKey=API_KEY')
    .then((data) => {
      displayRecipes.push(data); // JSON data parsed by `response.json()` call
      console.log(displayRecipes)
    });

})```

Ответы [ 2 ]

0 голосов
/ 25 марта 2020

Я нашел решение своей проблемы, я не уверен, что это лучший способ сделать это, но он работает нормально для меня. так что дом выглядит следующим образом: (я добавил onclick к кнопке поиска)

<div id="container">
        <!-- first input for the first ingrediant you can search -->
        <input type="text" class="ingInput" id="id" placeholder="ingrediant" onfocus="auto(this)">
    </div>
    <!-- search button, first bring the recipies based on ingredient, then the full recipies based on ids from the first fetch data -->
    <button  id="search" onclick="asyncCall()">Search</button>

    <!-- add new input for more ingrediant -->
    <button id="add" onclick="add()">Add</button>

    <!-- display the element i have created from the data i have -->
    <div id="display">

    </div>
    <!-- for jquery pagination -->
<button id="btn_prev">Prev</button>
<button id="btn_next">Next</button>
page: <span id="page"></span>

и javascript для получения данных (сначала по первой ссылке API, затем со второй ссылки API):

//recipies by ingredients array
var displayData = [];

//full recipies array
var displayRecipes = [];

async function search(){

  var l = document.getElementsByClassName("ingInput").length
  var ing = document.getElementById('id').value
  var ing1 = ''
  //getting all the values from the inputs so i can search it in the api url
  for(var i = 1; i<l ;i++){
    ing1 += ',' + document.getElementsByClassName("ingInput")[i].value 
  }

  //the api url with the inputs values for searching by ingredeints
 await fetch('https://api.spoonacular.com/recipes/findByIngredients?ingredients='+ ing + ing1 + '&number=10&apiKey=API_KEY', {
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    }
  }).then(res => res.json())
    .then((data) => {
      displayData.push(data); // JSON data parsed by `response.json()` call
      console.log('done')
    });   
}

async function getRecipes(){
  var l = displayData[0].length
  var ids = []
  for(var i = 0; i<l ;i++){
    ids.push(displayData[0][i].id) 
  }
  await fetch('https://api.spoonacular.com/recipes/informationBulk?ids='+ids.toString()+'&apiKey=API_KEY',{
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
    .then(res => res.json())
    .then((data) => {
      displayRecipes.push(data); // JSON data parsed by `response.json()` call
      console.log(displayRecipes)
    });   
}

async function asyncCall() {
  console.log('calling');
  const resultSearch = await search();
  console.log('done await search');

  console.log('calling2');
  const resultRecipies = await getRecipes();
  console.log('done await recipes');

}```
0 голосов
/ 24 марта 2020

Как насчет второй выборки, только если у вас есть данные из первой? Таким образом, когда данных не существует, кнопка выбирает исходные данные. Если данные уже существуют, он получает дополнительную информацию. Итак, у вас есть один слушатель:

 document.getElementById( "search" ).addEventListener( "click", function () {
    if ( displayData.length === 0 ) {
        // Call first function 
    } else {
        // Call second function
    }
 })
...