简体   繁体   中英

How to call a function in Javascript after a for-loop finishes?

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();
};

This stems from the fact that the foreach loop does not honor the await clause, it just keeps iterating. You can use a for...of loop which should honor the await but has the downside that every call waits for the previous to finish. To make the ajax calls in parallel you can use await Promise.all() see Any difference between await Promise.all() and multiple await?

Possible duplicate of: Using async/await with a forEach loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM