Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Created May 29, 2018 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ugarz/e36f424b3ff62af5f87a6d5eb97f69c8 to your computer and use it in GitHub Desktop.
Save Ugarz/e36f424b3ff62af5f87a6d5eb97f69c8 to your computer and use it in GitHub Desktop.
Workflow to process a bunch of users

Workflow to process a bunch of users

How to process users recovered from a database going down the array of users until there is no more of them.

// Act like it is a database
const users = [
    { name: "ugo", age: 28 },
    { name: "camille", age: 25 }
]

// Fetch users from fake database
function _fetchUsers() {
    return new Promise((res,rej) => {
        console.log('** Fetching users')
        setTimeout(() => {
            console.log('** Found users', users)
            res(users)
        }, 1500);
    })
}

// Do something on users
function processAllUsers() {
    console.log('** Starting the app');
    return _fetchUsers()
        .then(users => waitForEach(user => logName(user), users))
        .catch(e => console.error('Oops:', e))
}

// Function to execute on each user
const logName = user => {
    return new Promise((res, rej) => {
        console.log('** The name is: ', user.name)
        res(user.name)
    })
};

/**
 * Recursive call on each element from the passed array
 * @param {function} processFunc 
 * @param {array} array to use
 */
const waitForEach = (processFunc, [head, ...tail]) =>
    !head
        ? Promise.resolve()
        : processFunc(head).then(waitForEach(processFunc, tail))

processAllUsers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment