Promise.all()一次获取所有请求,而不是一个接一个地获取



我正在尝试一个接一个地进行多次提取,然后逐个处理结果。我试着按照其他几个问题中描述的那样做,但不知怎么的,我的获取都是同时启动的,这使我的功能失效。

let counter = 0;
let rounds = selectedTypes.length;
Promise.all(selectedTypes.map((type) => {
let body = {
selectedScreenshot: type,
dataUrl: dataUrl
};
console.log(type);
return fetch(URL, {
method: 'POST',
body: JSON.stringify(body),
credentials: 'same-origin',
})
.then((resp) => {
counter++;
var pleaseWait = document.getElementById('please-wait');
pleaseWait.innerText = `Please wait - ${counter} of ${rounds} done!`;
console.log(counter);
return resp.text();
}) // Transform the data into json
.catch(err => console.log(err))
.then(function (data) {
console.log('data: ', data);
console.log('next');
return data;
})
.catch(err => console.log(err));
}
)).then(urls => {
console.log('done', urls);
})

"类型"打印输出是在我启动所有选定类型的功能后直接完成的。然而,我希望记录类型,然后是"数据",然后"下一个",然后是第二个类型。当一切都完成时,它应该打印"完成"和所有URL。

我在这里做错了什么?

您可以使用。。和async/await一起等待每个调用完成,然后再转到下一个调用。。

例如:

const URL = 'https://httpbin.org/post';
const dataUrl = 'dataUrl';
const selectedTypes = [...Array(10).keys()].map(n => `type${n}`);
let counter = 0;
let rounds = selectedTypes.length;
function delay(delayMs) {
return new Promise(resolve => setTimeout(resolve, delayMs));
}
async function postData() {
let result = [];
for (let type of selectedTypes) {
let body = {
selectedScreenshot: type,
dataUrl: dataUrl
};
console.log(type);
try {
console.info(`Making fetch call #${(counter||0)+1} of ${selectedTypes.length}`);
const resp = await fetch(URL, {
method: 'POST',
body: JSON.stringify(body),
credentials: 'same-origin',
});
// Get the text data (JSON)
const data = await resp.text();
counter++;
var pleaseWait = document.getElementById('please-wait');
pleaseWait.innerText = `Please wait - ${counter} of ${rounds} done!`;
console.log(counter);   
result.push(data);
// Only adding this in to slow demo down.. we can remove in production.
await delay(1000);
} catch (err) {
console.err('An error has occurred:', err);
throw err;
}
}
console.log("done:", result);
}
// If any request fails the error will bubble up to here (as a result of re-throwing the error in the catch block. If we omitted the try/catch we'd get much the same behaviour.
postData().catch(err => console.log("Top level error:", err));
<html lang="en">
<head>
<script src="test-fetch-foreach.js"></script>
</head>
<body>
<div id="please-wait"></div>
</body>
</html>

最新更新