[英]Execute a sequentially function that executes fetch
我需要順序執行handleCursor
。 我怎樣才能做到這一點?
handleCursor
正在發出獲取請求,並且看起來像在獲取api請求和WriteData完成之前就返回了。 我能找到的“修復它”的唯一方法是將所有內容放到一個大函數中,但這看起來非常丑陋。
function Fill(cursor, diff ){
for (var i = 0; i < diff; i++) {
// get the latest html htmlNode written by WriteData
let htmlNode = document.querySelect("lastCursorElem");
const cursor = cursorHistory.top.pop();
try{
handleCursor(cursor, htmlNode);
}
catch(err) {
console.log(err);
return;
}
}
return;
};
function handleCursor(cursor, htmlNode){
fetch(cursor).then(
function(response) {
switch (response.status) {
case 200:
response.text().then(function(data) {
var next = response.headers.get("next");
WriteData(next, data, htmlNode) ;
return;
}).
catch(function(err) {
console.log('Fetch Error :-S', err);
});
break;
default:
return;
}
}
).
catch(function(err) {
console.log('Fetch Error :', err);
});
}
可能是這樣的(未經測試):
async function Fill (cursor, diff) {
for (var i = 0; i < diff; i++) {
// get the latest html htmlNode written by WriteData
const htmlNode = document.querySelector('lastCursorElem')
const cursor = cursorHistory.top.pop()
try {
const response = await fetch(cursor)
const data = await response.text()
if (res.ok) {
WriteData(response.headers.get('next'), data, htmlNode)
} else {
console.log('response was not 200-299')
}
} catch (err) {
console.log(err)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.