如何获得递归功能接受承诺等待?

发布于 2025-01-19 19:46:57 字数 991 浏览 1 评论 0原文

我正在尝试从数据库中获取信息,其中这些信息以多页为单位,所有这些信息都需要将其编译到一个数组中。

但是,即使我正在处理诺言,但我递归地使用该功能来调用该函数,然后它仍然不拭目以待,并期望“下一页”阵列,然后才能抓住它。

以下是相关的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘年祭陌 2025-01-26 19:46:57

您的getallpersonevents永远不会返回任何东西。然后您的然后处理程序可以,但不是getallpersonevents。为了做您所描述的事情,您需要从数组中实现的诺言。

坚持您的明确承诺回调,您可以这样做(请参阅注释):

function getAllPersonEvents(jobID, pageNum) {
    // An array to build up our results in
    const all = [];
    // Get the initial events
    return getPersonEvents(jobID, pageNum).then((page) => {
        all.push(...page);
        if (page.length < 100) {
            // We have all of them, fulfill the promise with the full array
            return all;
        } else {
            // There may be more, recurse...
            return getAllPersonEvents(jobID, pageNum + 1).then((page) => {
                // ...and then add the results from the recursion to our
                // own, and fulfill this promise (which fulfills the main
                // one) with `all`.
                all.push(...page);
                return all;
            });
        }
    });
}

使用async/等待,更简单地写作要简单得多:

function getAllPersonEvents(jobID, pageNum) {
    const all = [];
    let page;
    do {
        page = await getPersonEvents(jobID, pageNum++);
        all.push(...page);
    } while (page.length >= 100);
    return all;
}

Your getAllPersonEvents never returns anything. Your then handler does, but not getAllPersonEvents. 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):

function getAllPersonEvents(jobID, pageNum) {
    // An array to build up our results in
    const all = [];
    // Get the initial events
    return getPersonEvents(jobID, pageNum).then((page) => {
        all.push(...page);
        if (page.length < 100) {
            // We have all of them, fulfill the promise with the full array
            return all;
        } else {
            // There may be more, recurse...
            return getAllPersonEvents(jobID, pageNum + 1).then((page) => {
                // ...and then add the results from the recursion to our
                // own, and fulfill this promise (which fulfills the main
                // one) with `all`.
                all.push(...page);
                return all;
            });
        }
    });
}

It's much simpler to write using async/await, though:

function getAllPersonEvents(jobID, pageNum) {
    const all = [];
    let page;
    do {
        page = await getPersonEvents(jobID, pageNum++);
        all.push(...page);
    } while (page.length >= 100);
    return all;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文