Async Generators

I found a practical use of Javascript generator functions .

I needed to retrieve all users from Cognito and then filter them based on a custom attribute’s value. Cognito returns a maximum of 60 users per call and provides a PaginationToken for additional users. This token can be used to fetch more users.

So this is the solution I came up with.

   async function* getAllCognitoUsers() {
       let startToken = `INITIAL`
       const options = { limit: 60, UserPoolId:`user-pool-id` }

       while(startToken) {
            if(startToken !== 'INITIAL') {
                options.PaginationToken = startToken
            }

            const response = await AdminCognitoUserPool.listUsers(options)

            startToken = response.PaginationToken
            startToken = startToken ? startToken.replace(/ /g, '+'): null;

            yield response.Users
       }
                
   }

AdminConginitoUserPool is Cognito instance. The function basically calls the Cognito API then uses to PaginationToken to decide if there are more users to be retrieved and then yield the retrieved users.

Since getAllCognitoUsers is a generator, it is iterable and can be used with for of loop.

    for await (const users of getAllCognitoUsers()) {
       console.log(users)
    }

This implementation efficiently handles user retrieval from Cognito using JavaScript generator functions.