我不熟悉javascript。实际上,我有一个基本的想法。我想提出一些请求,在这些请求继续的同时,我想在另一个函数中处理传入的数据。
这是我的获取函数。这有点递归。在5个请求之后,它将结束。
function loadNextContainer() {
var url = "sample_videos/container" + numberContainer;
if(numberContainer>4){
return;
}
fetch(url)
.then(response => response.blob())
.then(data => {
console.log("fetched");
//i ll add the fetched data to array or something else
})
.catch((error) => {
console.error('Error:', error);
});
numberContainer++;
loadNextContainer();
}
你可以想象这就是流程代码。
async function loop1() {
for (let i = 0; i < 5; i++) {
console.log(i);
await null;
}
}
输出:
0
1
2
3
4
fetched
fetched
fetched
fetched
fetched
这就是我想要的:
fetched
0
fetched
1
fetched
2
3
fetched
4
fetched
他们按顺序工作并不重要。他们只需要一起工作。
您可以在下面的代码段中使用Promise.all()
,这应该可以解决您的问题,函数fetch1
和fetch2
同时运行。
const fetch1 = async() => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1")
const json = await res.json()
return json
}
const fetch2 = async() => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/2")
const json = await res.json()
return json
}
const main = async() => {
const results = await Promise.all([fetch1(), fetch2()])
console.log(results)
}
main().catch(e => console.log(e.message))