如何使用 javascript 获取每个请求

How to get every request with javascript

我尝试发送请求超过 1 次,有时我收到所有请求,有时我只收到 8 个请求中的 7 个,等等。这是示例和代码,我尝试使用 promise all 但它说 tat Promise。都不急躁

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

您需要将提取重构为一个单独的函数,returns 承诺获得单个结果。

然后您可以创建所有这些承诺,然后 await 实现它们,然后处理它们。

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