(JavaScript) Synchronizing forEach Loop with callbacks inside

前端 未结 5 2109
无人及你
无人及你 2020-12-08 02:24

I am doing some computations inside a double forEach Loop something like this:

array.forEach(function(element){
    Object.keys(element).forEach         


        
5条回答
  •  温柔的废话
    2020-12-08 03:16

    For browsers which support Promise (or using polyfill) / nodejs I've implemented my self a sync version of forEach with callbacks, so I'll just share that here..

    The callback must return a promise..

    function forEachSync(array, callback) {
        let lastIndex = array.length - 1;
        let startIndex = 0;
    
        return new Promise((resolve, reject) => { // Finish all
            let functionToIterateWith = (currIndex) => {
                if (currIndex > lastIndex) {
                    return resolve();
                } else {
                    callback(array[currIndex]).then(() => {
                        functionToIterateWith(currIndex + 1);
                    }).catch(err => reject(err));
                }
            }
    
            functionToIterateWith(startIndex);
        });
    }
    

提交回复
热议问题