1

I need to pull data from an API, but it sends me the data in pages of 100 + the total count of results. The way I tried doing is

let count, page = 0;
do {
    ++page
    pullData(page, () => {
        count = data.count
    });
} while (page < count / 100);

but the code checks the condition of the loop before count is initialized (page < undefined / 100), and the loop ends up running only the first time.

Is there a way to make the loop wait for the async body to run before checking the condition?

4
  • 1
    Well, you can use await. Commented Nov 19, 2020 at 5:03
  • I tried both await count = data.count and await pullData with no success Commented Nov 19, 2020 at 5:16
  • If pullData returns a promise that should work, but if it expects a callback function then you need to "promisify" it first. Commented Nov 19, 2020 at 5:21
  • For await to work, pullData must return a Promise, and await keyword must be used inside function with async keyword before function, like async function Foo () .... Commented Nov 19, 2020 at 5:21

1 Answer 1

1

Use async/await or recursive functions like this:

const recursive = (page) => {
    pullData(page, () => {
        count = data.count;
        if (page < count / 100) {
            recursive(++page)
        }
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.