First of all, having native promises since ES6, I think that it is not a good idea to use a library unless you have to support old browsers or old nodejs versions.
When you work with promises, you are working with asynchronous code, so, you can loop in different ways.
Imagine you have this snippet:
function step1 (item){
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('step 1 for item ' + item);
}, 1000);
});
}
function step2 (item){
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('step 2 for item ' + item);
}, 1000);
});
}
function step3 (item){
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('step 3 for item ' + item);
}, 1000);
});
}
function processItem (item) {
return step1(item).then(result =>{
console.log(result);
return step2(item);
}).then(result =>{
console.log(result);
return step3(item);
}).then(result =>{
console.log(result);
return ('finished process of item ' + item);
}).catch(err =>{
throw (err);
});
}
where the processItem function will be applied to an items array.
The code above is asynchronous, so, when you run it, then inmediatly the next one is executed, so, if the processItem function takes 3 seconds to finish, and you want to apply that function to 10 items, it will take 3 seconds because the Promise call will be executed secuentially, but without waiting to finish any of the them.
Example code:
function promiseFor(set, fn){
return new Promise((resolve, reject) => {
return arr.map(item => ()=> fn(item)).forEach(proc => {
return proc().then(res => {
resolve();
}).catch(err=>{
console.log(err);
});
});
});
}
- B. run the promises in sequence.
The sequence not will start to execute any promise until the previous one has been executed, this is like a non asynchronous foor loop:
Example:
function sequence (set, fn){
return set.map(item => ()=> fn(item)).reduce((curr, next)=> {
return curr.then(()=>{
return next();
})},Promise.resolve());
}