Callback as num_rows and break if statement meets

Viewed 52

I need help, I have n data where is returned by ajax request to client. Each row of data I need to call an api from other app. Now I am using callback for that, and yes the api is success and give value as I expected. But I got some little problem. I have number of limitation for accessing the api per day, so what I want is if callback for api is responding some error_code like out of quota or any error code so for next row data I don't want to call the api again. My code like below:

$("#verifyMe").submit(function(event) {
    var isError = false;
    var formDatas = new FormData($('#verifyMe')[0]);
    // getting my row Data (SELECT * FROM table)
    $.ajax({
    ....
    success: function(kis) {
        for (var i = 0; i < kis.data.length; i++) { // loop as many row data
            // call api as long as no break
            console.log(isError); // always be false
            checking(kis.data[i].id, function(output){ // api returning object
                if(output.error_code) {
                    console.log(isError); // last value
                    isError = true; // only affect in callback bracket
                    console.log(isError); // true
                    break; // break for loop calling the api
                }
            } // end of callback bracket
            // I think the break; should goes this line but error_code will undefined bc out of callback function
        }
    }    
    });
});

I think the problem is because asynchronous. The error_code in callback will always undefined/null out of that callback, and break; will works if it is in for loop bracket (in example code I show it is in callback bracket). Sorry if my explanation is not clear enough. Thank you

1 Answers

You can easily implement your requirements using Promise.each() of the bluebird library. Using this function, you can execute asynchronous functions sequentially.

var Promise = require('bluebird');
...
$.ajax({
    ....
    success: function(kis) {
            Promise.each(kis.data, (oneData) => {
                return new Promise((resolve, reject) => {
                    // It will be performed sequentially
                    checking(oneData.id, function(output){ // api returning object
                        if(output.error_code) {
                            reject(output.error_code); // break for loop calling the api
                        }
                        // Success case
                        resolve();
                    });
                });
            })
            .then(result => {
                // Will be called when all kis.data have been successfully processed
            })
            .catch(error => {
                // Will be called when an error occurs in the kid.data
            });
        }
    }    
});

Related