Search code examples
javascriptphpfetch-api

How to get every request with javascript


I'm trying to send requests more than 1 time and sometimes I get all requests sometimes I get only 7 of 8 and etc. Here is the example and code, I try with promise all but it says tat Promise. all are not irritable.

function requestToSend(nums_to_print) {
  if (
    nums_to_print > 8 ||
    nums_to_print < 1 ||
    nums_to_print == '' ||
    nums_to_print == null
  ) {
    errorArray.push(
      'Entered lucky combinations ' +
        nums_to_print +
        ' cannot be greater than 8.'
    );
  } else {
    let results = document.getElementById('results');

    for (let i = 1; i <= nums_to_print; i++) {
      fetch('generateNumbers.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          nums: nums_to_print,
        }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data['error']) {
            let error = [];
            error.push(data['error']);
            errorToDisplay(error);
          }

          if (data) {
            let str = document.createElement('p');

            for (let y = 0; y < data.length; y++) {
              str.innerText = i + '. ' + data[y];
            }

            results.appendChild(str);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }

    results.innerHTML = '';
  }

  errorToDisplay(errorArray);
}

Example


Solution

  • You'll want to refactor the fetch to a separate function that returns the promise for a single result.

    Then you can create all of those promises, then await for their fulfillment, then process them.

    function generateNumbers(nums_to_print) {
      return fetch('generateNumbers.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          nums: nums_to_print,
        }),
      }).then((res) => res.json());
    }
    
    async function requestToSend(nums_to_print) {
      if (
        nums_to_print > 8 ||
        nums_to_print < 1 ||
        nums_to_print == '' ||
        nums_to_print == null
      ) {
        errorToDisplay(
          'Entered lucky combinations ' +
            nums_to_print +
            ' cannot be greater than 8.'
        );
        return;
      }
      const resultsDiv = document.getElementById('results');
      resultsDiv.innerHTML = '';
      const promises = [];
      for (let i = 1; i <= nums_to_print; i++) {
        promises.push(generateNumbers(nums_to_print));
      }
      const results = await Promise.all(promises);
      results.forEach((data, i) => {
        if (data.error) {
          errorToDisplay(data.error);
        } else {
          const str = document.createElement('p');
          for (let y = 0; y < data.length; y++) {
            str.innerText = i + 1 + '. ' + data[y];
          }
          resultsDiv.appendChild(str);
        }
      });
    }