The best pattern for handling async looping in Node.js

前端 未结 3 541
有刺的猬
有刺的猬 2021-01-03 00:01

I\'m new to Node and trying to ensure that I\'m using sane designs for a JSON-driven web app.

I\'ve got a bunch of data stored in Redis and am retrieving it through

3条回答
  •  天涯浪人
    2021-01-03 00:33

    You can use the async library, it provides some handy methods for looping, such as forEach:

    forEach(arr, iterator, callback)

    Applies an iterator function to each item in an array, in parallel. The iterator is called with an item from the list and a callback for when it has finished. If the iterator passes an error to this callback, the main callback for the forEach function is immediately called with the error.

    Note, that since this function applies the iterator to each item in parallel there is no guarantee that the iterator functions will complete in order.

    Example

    // assuming openFiles is an array of file names and saveFile is a function
    // to save the modified contents of that file:
    
    async.forEach(openFiles, saveFile, function(err){
        // if any of the saves produced an error, err would equal that error
    });
    

提交回复
热议问题