如何获得递归功能接受承诺等待?
我正在尝试从数据库中获取信息,其中这些信息以多页为单位,所有这些信息都需要将其编译到一个数组中。
但是,即使我正在处理诺言,但我递归地使用该功能来调用该函数,然后它仍然不拭目以待,并期望“下一页”阵列,然后才能抓住它。
以下是相关的代码:
function getAllPersonEvents(jobID, pageNum) {
getPersonEvents(jobID, pageNum).then(function(val){
if (val.length < 100) {
console.log(val);
console.log("above returned");
return val;
} else {
console.log("expecting return!");
let nextPages = getAllPersonEvents(jobID, pageNum + 1);
console.log(nextPages);
let allEvents = val.concat(nextPages);
console.log(allEvents);
return allEvents;
}
});
}
function getPersonEvents(jobID, pageNum) {
return fetch('WORKING FETCH URL' + pageNum + '&job_ids[]=' + jobID, options)
.then(response => response.json())
.then(response => {
return response.person_events;
})
.catch(err => console.error(err));
}
如何到达“上述返回!”代码 “期望返回!”部分?
I am trying to get information from a database, where the information comes in multiple pages and all of it needs to be compiled to a single array.
However, even though I'm in a .then for handling the promise and I recursively call the function using the .then, it still doesn't wait and expects the "next page" array before I can grab it.
Below is the relevant code:
function getAllPersonEvents(jobID, pageNum) {
getPersonEvents(jobID, pageNum).then(function(val){
if (val.length < 100) {
console.log(val);
console.log("above returned");
return val;
} else {
console.log("expecting return!");
let nextPages = getAllPersonEvents(jobID, pageNum + 1);
console.log(nextPages);
let allEvents = val.concat(nextPages);
console.log(allEvents);
return allEvents;
}
});
}
function getPersonEvents(jobID, pageNum) {
return fetch('WORKING FETCH URL' + pageNum + '&job_ids[]=' + jobID, options)
.then(response => response.json())
.then(response => {
return response.person_events;
})
.catch(err => console.error(err));
}
How do I get to the "above returned!" code before the "expecting return!" part?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
getallpersonevents
永远不会返回任何东西。然后您的然后
处理程序可以,但不是getallpersonevents
。为了做您所描述的事情,您需要从数组中实现的诺言。坚持您的明确承诺回调,您可以这样做(请参阅注释):
使用
async
/等待
,更简单地写作要简单得多:Your
getAllPersonEvents
never returns anything. Yourthen
handler does, but notgetAllPersonEvents
. In order to do what you've described, you'll want to return a promise from it that will be fulfilled with the array.Sticking with your explicit promise callbacks, you can do it like this (see comments):
It's much simpler to write using
async
/await
, though: