Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active March 20, 2018 13:15
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/49352b90d959ad24dccadbb2f20b196d to your computer and use it in GitHub Desktop.
Save Ugarz/49352b90d959ad24dccadbb2f20b196d to your computer and use it in GitHub Desktop.
Recursion with node to process on each item from an array

Recursion on array with Promises

Sometime you just want to do operations on a bunch of datas. Oh wait, there is Promises to resolve before.. Here is a simple proposal to solve it.

// 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))
}

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