Execute Tasks in the Loop

October 14, 2017

Execute Tasks In the Loop Using Async.each

Now I am going to show you how to execute asynchronous Tasks In the Loop by using async.each

const Client = require('node-rest-client').Client;

const restClientService = new Client();

restClientService.registerMethod('getPosts', 'http://jsonplaceholder.typicode.com/users/1/posts', 'GET');

restClientService.registerMethod('getAlbums', 'http://jsonplaceholder.typicode.com/users/1/albums', 'GET');

restClientService.registerMethod('getPhotos', 'http://jsonplaceholder.typicode.com/albums/1/photos', 'GET');

export default restClientService;

 

function loopDemo(req, res, next) {
    let users = [1, 2, 3, 4, 5, 6];
    let results = [];

    async.each(users, (userId, cb) => {

        RestClientService
            .get(`http://jsonplaceholder.typicode.com/users/${userId}/posts`,
                (posts, response) => {
                    if (response.statusCode !== 200) {
                        return cb('Unable to fetch the posts');
                    }
                    results.push(posts);
                    return cb();
                });
    }, err => {
        if (err) {
            return res.status(500).send(err);
        }
        return res.json(results);
    })

Async.each always take an array of functions. The second argument will be iterator function. This iterator function run for every item of the collection. I have an array of userId. I want to get all the posts for six users. If you get an error and your response is not equal to 200. I am calling the callback with the error value. It is immediately returned and run the final callback method with an error value.

You can see that I am adding posts array to results collection. So, results array will have the six posts elements. Each item will be an array of posts. If you are using callbacks, then Async.each is the best method to run tasks in the loop.

About the author

Haider Malik

Click here to add a comment

Leave a comment: