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()