我目前正在尝试循环运行一个函数。
无法弄清楚,这是我尝试过的:
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
});
关于javascript - 循环运行一个函数直到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494598/