【发布时间】: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