JavaScript, Node.js: is Array.forEach asynchronous?

后端 未结 10 1442
时光说笑
时光说笑 2020-11-22 10:47

I have a question regarding the native Array.forEach implementation of JavaScript: Does it behave asynchronously? For example, if I call:

[many          


        
10条回答
  •  清酒与你
    2020-11-22 11:53

    Use Promise.each of bluebird library.

    Promise.each(
    Iterable|Promise> input,
    function(any item, int index, int length) iterator
    ) -> Promise
    

    This method iterates over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where the value is the resolved value of a respective promise in the input array. Iteration happens serially. If the iterator function returns a promise or a thenable, then the result of the promise is awaited before continuing with next iteration. If any promise in the input array is rejected, then the returned promise is rejected as well.

    If all of the iterations resolve successfully, Promise.each resolves to the original array unmodified. However, if one iteration rejects or errors, Promise.each ceases execution immediately and does not process any further iterations. The error or rejected value is returned in this case instead of the original array.

    This method is meant to be used for side effects.

    var fileNames = ["1.txt", "2.txt", "3.txt"];
    
    Promise.each(fileNames, function(fileName) {
        return fs.readFileAsync(fileName).then(function(val){
            // do stuff with 'val' here.  
        });
    }).then(function() {
    console.log("done");
    });
    

提交回复
热议问题