I'm trying to run multiple checks through the for-loop. Sometimes within the loop I have to run an AJAX-request. To check if that is finished I'm using the waitForIt function.
After the for-loop is finished. I want to run the InitAndSeachItems function. But the function always runs while the loop is still running.
I have tried await and a variation of the waitForIt function, but i can not get it to work async. I want to stay away from using sleep, since that is not clean coding. Can someone give me some advice please?
See the codeblock for the function I am running. var bool is set to false after the AJAX-call is finished in another function and works fine. The focus here is about running the initAndSeachItems function at the correct timing.
    this.setFavorietFromJsonString = async function(filterJson) {
    /** set variables */
    filterJson = JSON.parse(filterJson);        /** loop through keys of json object */
    for (var key in filterJson) {
        /** set variables */
        var selectedValues = filterJson[key];
        /** loop through values of the keys */
        Object.keys(selectedValues).forEach(await function(index) {
            /** give input checked true */
            if($('.'+key+'Items#'+selectedValues[index]).length > 0) {
                $('.'+key+'Items#'+selectedValues[index]).prop('checked', true);
            } else {
                bool = true;
                $('#'+key+'Lijst').val(selectedValues[index].replace('-', ' '));
                window["groteFilterSearch"+key](true);
                waitForIt(key, selectedValues[index]);
                async function waitForIt(key, value){
                    if (bool === true) {
                        setTimeout(function(){waitForIt(key, value)},100);
                    } else {
                        setTimeout(function(){
                            $('.'+key+'Items#'+value).prop('checked', true);
                            bool = false;
                        },200);
                    };
                }
            }
        });
    }
    /** set init of listing */
    initAndSearchItems();
};
 
    