问题与foreach循环的有效形式的承诺

时间:2019-07-12 09:13:54

标签: javascript foreach promise async-await

我之所以来找你,是因为我需要帮助才能在foreach循环中使用promise。

我试图验证表单上的每个输入。一些输入需要使用ajax请求进行验证,因此我需要帮助才能使用promise。

我尝试推迟,promise.all,但没有任何效果,实际上,表单是在所有ajax请求完成之前提交的。

感谢您的帮助!

btSubmit.on('click', async (e) => {
                e.preventDefault();
                e.stopPropagation();

                let check = await checkForm(form);

                console.log('----- SUBMIT FORM -----', check);

            });

async function checkForm(form) {
                var promises = [];
                console.log('before foreach');
                await $.each(form[0], async (index, champs) => {
                    if (champs.hasAttribute('required')) {
                        console.log('before callback', champs.name);
                        await options.callback(champs);
                        console.log('after callback', champs.name);
                    }
                });
                console.log('after forEach');
            }
...
callback: (champs) => {
            var result = true;
            if (!champs.checkValidity()) {
                champs.classList.add('is-invalid');
                result = "Ce champs est obligatoire";
            } else {
                if (champs.name == 'matricule') {
                    console.log('--- start matricule');
                    result = verifMatricule(champs.value);
                    console.log('--- stop matricule');
                }
            }
            return result;
        }

function verifMatricule(valeur) {
    var data = {champsATester: 'matricule', matricule: valeur};
    return $.ajax({
        url: "ajax/users/ajax.gestion_utilisateur.php",
        dataType: 'text',
        data: data,
        type: 'post'
    });
}

0 个答案:

没有答案
相关问题