【问题标题】:How to get every request with javascript如何使用 javascript 获取每个请求
【发布时间】:2021-11-16 04:16:26
【问题描述】:

我尝试发送请求超过 1 次,有时我收到所有请求,有时我只收到 8 个中的 7 个等等。这是示例和代码,我尝试全部承诺,但它说的是承诺。所有人都不烦躁。

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

【问题讨论】:

  • 您的代码没有等待所有异步获取调用完成。
  • 我怎样才能做到这一点?

标签: javascript php fetch fetch-api


【解决方案1】:

您需要将 fetch 重构为一个单独的函数,该函数返回单个结果的 Promise。

然后您可以创建所有这些承诺,然后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);
    }
  });
}

【讨论】:

  • 我试试你的代码,我又遇到了同样的问题
  • 未捕获(承诺中)语法错误:JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束
  • 您需要修复您的 PHP 脚本以返回正确的 JSON。
  • codeshare.io/9OjAP4 这里是 php
  • 查看浏览器控制台的网络检查器,看看响应是否正确。
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多