在forEach

时间:2019-03-10 17:22:59

标签: javascript jquery

每次forEach迭代后,我不必等待(等待)。我没有正确的程序。 目前,代码按以下顺序执行:

Load: en
Load: ru
Complete load (en)
Complete load (ru)

我需要这样:

Load: en
Complete load (en)
Load: ru
Complete load (ru)

此代码应与jquery一起使用(从服务器加载数据),但是我对代码进行了重新设计,以便直接从代码中获取数据

/*
	Offline mode start
*/
var files = {
    "/public/js/json/languages.json": {
        "en": {
            "needInclude": true,
            "link": "/js/json/languages/english.json"
        },
        "ru": {
            "needInclude": false,
            "link": "/js/json/languages/russian.json"
        }
    },
    "/js/json/languages/english.json": {
        "general": {
            "authorization": "Authorization",
            "username": "Username",
            "password": "Password",
            "signin": "Sign In",
            "signup": "Sign Up",
            "restorepassword": "Restore password"
        }
    },
    "/js/json/languages/russian.json": {
        "general": {
            "authorization": "Авторизация",
            "username": "Логин",
            "password": "Пароль",
            "signin": "Войти",
            "signup": "Зарегистрироваться",
            "restorepassword": "Восстановить пароль"
        }
    }
}

function loadFile(url, doneFunction = function() {}) {
    doneFunction(files[url]);
}
/*
	Offline mode end
*/

/*
	Main code start
*/
function loadLanguage(url, overwrite = false) {
    return new Promise(resolve => {
        //$.get(url).done(function(language){
        loadFile(url, function(language) {
            try {
                Object.keys(language).forEach(function(key1) {
                    if (!isset(lang[key1])) {
                        lang[key1] = language[key1];
                    } else {
                        Object.keys(language[key1]).forEach(function(key2) {
                            if (!isset(lang[key1][key2]) || overwrite) {
                                lang[key1][key2] = language[key1][key2];
                            }
                        });
                    }
                });
                resolve(true);
            } catch (err) {
                resolve(false);
            }
        });
    });
}

function selLanguage(language) {
    //$.get("/public/js/json/languages.json").done(async function(languages){
    loadFile("/public/js/json/languages.json", function(languages) {
        Object.keys(languages).forEach(lang => {
            return new Promise(async resolve => {
                if (lang == language || languages[lang]["needInclude"] == true) {
                    console.log("Load: " + lang);
                    await loadLanguage(languages[lang]["link"], lang == language);
                    console.log("Complete load (" + lang + ")");
                    resolve();
                }
            });
        });
    });
}
/*
	Main code end
*/
selLanguage("ru");

0 个答案:

没有答案