Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

angularjs promise .then() to run sequentially inside a for loop

function somethingAsync(value) {
    return new Promise(res => setTimeout(res, 500, value * value));
}

function processInputInSeries(input) {
    function processNext(index, input, results) {
        if (index >= input.length) return results;
        return somethingAsync(input[index]).then(function (result) {
            return processNext(index + 1, input, [...results, result]);
        });
    }

    return processNext(0, input, []);
}

const resultPromise = processInputInSeries([1,2,3]);
resultPromise.then(function(results) { console.log(results) });
 
PREVIOUS NEXT
Tagged: #angularjs #promise #run #sequentially #loop
ADD COMMENT
Topic
Name
5+8 =