3

I am using the google api to get a list of all the messages in my mailbox. The API is paginating the list, and with every call it returns the next page, so I have to call it recursively:

const fetch = (cb, next) => {
    google.gmail('v1').users.messages.list({
        auth: oauth2Client,
        userId: 'me',
        pageToken: next
    }, cb)
}
const store = (err, result) => {
    // do something with result and then
    if (result.nextPageToken) {
        fetch(store, result.nextPagetToken)
    }
}

fetch(store)

Is there a better way to do this to avoid the recursion so I don't bust the stack?

2 Answers 2

1

Instead of:

fetch(store, result.nextPagetToken)

you can use:

process.nextTick(fetch, store, result.nextPagetToken);

but if something like that is already done in messages.list() callback then it may not even be necessary. Besides a proper tail call optimization is already supported in JS and is available in Node since version 6.5.0 when you use the --harmony flag, see:

And there is also my tco module for infinite recursion even in the oldest versions of Node.

Sign up to request clarification or add additional context in comments.

1 Comment

process.nextTick(fetch, store, result.nextPagetToken); looks like exactly what I was looking for. A bit scared to use tail-call-recursion, as I am afraid it will be too easy to break it at some point without noticing. Thanks.
1

I'm afraid I don't know the google API but generally speaking you should be looking at Promises:

Using Promises | Google API

2 Comments

Thanks. I was trying to avoid using promises.
Don't avoid it, and don't go ahead with the accepted answer until you've at least tried. Trust me: crack your knuckles and spend one afternoon learning promises. It's a 'pokemon evolution' style change to the language, you will never ever look back.

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.