N.Nicolas
N.Nicolas

Reputation: 23

Javascript Callback function in loop

I've 3 functions in Javascript. function1 insert data into an array-array_message', function2 export the 'array_message' into a csv file. The function3 call these two functions with all the elements in a list.

In Javascript, function2 is executed at the same time as function1, which makes that the exported file is always empty because no time to fill in the 'array_message'.

Could anyone help how to call function2 when function1 is done in this 'for' loop? Maybe another callback function?

 function function3(){
      for (var i=0; i<list.length;i++){
        console.log(list[i]);
        function1(list[i])
        function2(list[i]+'.csv',array_message)
      }
     }

Upvotes: 2

Views: 3662

Answers (1)

Rob M.
Rob M.

Reputation: 36511

You could utilize Promises (preferrable IMO) or a callback to accomplish this:

function function1(item) {
    return new Promise(function(resolve, reject) {
        // do operations
        if (operationSuccessful) {
            resolve(dataFromOperation);
        } else {
            reject(errorFromOperation);
        }
    });
}

function function3() {
    for (var i=0; i<list.length;i++) {
        // only call function2 after function1 is complete
        function1(item[i]).then(function(responseData) {
            function2(responseData);
        }).catch(function(error) {
            console.error("Problem in function1")
        });
    }
}

Upvotes: 2

Related Questions