我想知道如何并行執(zhí)行動態(tài)獲取請求,我已經(jīng)嘗試了12個小時了,但我想不出答案,我到處查看了google和StackOverflow,我真的很累。
for (const fileindex of filelist) {
let dcmFilename = `slice_${fileindex}.dcm`
slices.push( {index:fileindex, filename:dcmFilename} )
fd.append(dcmFilename, files[fileindex], dcmFilename);
fd.append('slices', JSON.stringify(slices));
loopcount += 1
if (filecount == 24 || loopcount == filelist.length){
if (cursorPos !== false) {
let scaleFactor = Tegaki.scaleFactor;
cursorPos.x = parseInt(cursorPos.x / scaleFactor);
cursorPos.y = parseInt(cursorPos.y / scaleFactor);
fd.append('x', cursorPos.x);
fd.append('y', cursorPos.y)
}
// Get layer id from index
if (index !== -1) {
type = this.layerTypes[index]['id']
}
// switch mode from heuristic to pytorch vertebrae for vertebral bone
if (type === 'vertebral-bone' ){
mode='PyTorch-Vertebrae'
}
// Post to endpoint
let domain = window.location.origin.replace(':8080', ':5000')
let list = await fetch(`${domain}/segment?mode=${mode}&type=${type}`, { method: 'POST', body: fd })
let result = await list.json()
// do something with result
// finish then continue the loop and create new body and send a new request
// clear formdata and continue loop
fd = new FormData()
}
我發(fā)送了下面的fetch請求,其中為每個請求生成主體,主體從來都不是同一個主體,主體由函數(shù)動態(tài)生成。是否有一種方法可以一次發(fā)送所有請求,然后等待它們返回響應,然后繼續(xù)我的其余代碼?
您可以將
filelist.map()
與async
回調(diào)一起使用,而不是包含await
的for/of
循環(huán)。由于
.map()
只是盲目地迭代數(shù)組而不等待任何返回的承諾,因此它將從.map()
調(diào)用的所有async
回調(diào)返回一個承諾數(shù)組。這些承諾最初將無法實現(xiàn),所有fetch()
操作將同時為"in-flight。然后,您可以在返回的承諾數(shù)組上使用await Promise.all(...)
,以了解它們何時完成:注意#1:由于您現(xiàn)在并行運行多個fetch操作,因此任何處理其結(jié)果的代碼都不能共享變量。這段代碼中有幾個變量沒有顯示它們的聲明。這些聲明可能應該在這個循環(huán)中,帶有
let
或const
,因此循環(huán)的每個迭代都有一個新的變量,并且您不會在迭代之間共享變量,除非該變量顯式地應該在迭代之間累積。此循環(huán)中沒有本地聲明的可疑變量可能會受到并行操作的影響,包括filecount
、loopcount
、cursorPos
、index
、mode
fd
和type
。您沒有在此處顯示整個執(zhí)行上下文,因此我們無法看到足夠的內(nèi)容來對這些內(nèi)容提出完整的建議。注意#2:包含此
if (filecount == 24 || loopcount == filelist.length)
的代碼看起來可能容易出現(xiàn)問題。如果您試圖在所有迭代都完成時運行一些代碼,那么在Promise.all()
之后運行該代碼比嘗試檢測上一次迭代何時完成要好。記住,您的迭代現(xiàn)在不一定按順序進行,因為您正在并行運行它們。它們將按順序啟動,但不一定按順序完成。