![](/img/trans.png)
[英]Wait until 'for loop' or 'push' is complete then run function - Javascript
[英]Run a function in a loop until
我目前正在嘗試循環運行一個函數。
無法弄清楚,這是我嘗試過的:
do {
queryLastCursor(lastCursor).then(lastCursorResults => {
if (lastCursorResults.hasNext = false) {
hasNextPage = false;
}
console.log(hasNextPage);
})
} while (hasNextPage);
queryLastCursor
是一種調用 API 的方法。 當它返回數據時,它的值為hasNext
如果它返回 false 那么我想將hasNextPage
設置為false
。 預期的行為是它一次又一次地運行該函數,直到我們得到結果hasNext = false
。 知道我做錯了什么嗎?
如果您想在循環中執行異步過程,我建議遞歸執行:
const runQuery = () => {
queryLastCursor(lastCursor)
.then(result => {
if (result.hasNext) {
// recursively call itself if hasNext is true
runQuery();
}
});
}
runQuery();
假設您想返回一些數據,您可以執行以下操作:
const runQuery = async (data) => {
return queryLastCursor(lastCursor)
.then(result => {
if (!data) {
data = [];
}
// assuming you are returning the data on result.data
data.push(result.data);
if (result.hasNext) {
// recursively call itself if hasNext is true
return runQuery(data);
}
retun data;
});
}
runQuery()
.then(data => {
// data should be an array of all the data now
});
我會做這樣的事情:
const callApi = async () => {
let result = await someMagic();
while (result.hasNext) {
doSomethingwith(result);
result = await someMagic();
}
return result;
};
const myResult = await callApi();
雖然這看起來有風險,但我們總是得到 hastNext = true 是什么? 一些安全性似乎很好,比如 while 循環中的循環限制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.