async-foreach-js
Execute an asynchronous function sequentially in forEach
for an array.
- TypeScript Support: ✅
npm install async-foreach-js
Sample
This is an example with axios.
require('async-foreach-js');
const axios = require('axios');
const crawlingTargets = [
'https://apple.com',
'https://amazon.com',
'https://aws.amazon.com',
'https://github.com',
'https://npmjs.com'
];
let crawlingResults = [];
crawlingTargets.asyncForEach((element, next, escape) => (
axios.get(element)
.then((response) => {
crawlingResults.push(response);
next();
})
.catch((error) => {
console.error(error);
escape();
})
))
.then(() => console.log('Done!'))
.catch(() => console.error('The loop was stopped with an error.'));
Method
Array.prototype.asyncForEach((element: any, next: function[, escape: function, index: Number])
element
The current working element in the given array.next()
A function to call next element.escape([message: any])
A function to escape in the loop.index
The element's index in the given array.