我目前正在尝试循环运行一个函数。
无法弄清楚,这是我尝试过的:
do {
queryLastCursor(lastCursor).then(lastCursorResults => {
if (lastCursorResults.hasNext = false) {
hasNextPage = false;
}
console.log(hasNextPage);
})
} while (hasNextPage);
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
假设您想返回一些数据,您可以执行以下操作:
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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |