简体   繁体   English

试图解决jquery异步问题

[英]Attempting to solve jquery async issue

I am pretty new to javascript, and I am trying to work with mailgun's email validation feature and I am trying to get the validation to work (by ensuring the email data is intact prior to submission of a form. 我是javascript的新手,我正在尝试使用mailgun的电子邮件验证功能,我正在努力使验证工作(通过确保在提交表单之前电子邮件数据完好无损)。

https://github.com/mailgun/validator-demo https://github.com/mailgun/validator-demo

However I found that the function validation_success is always called asynchronously, resulting in the sequence as below: 但是我发现函数validation_success总是异步调用,导致如下序列:

checks start!
Feedback:390 checks complete! ErrorEmail=2
Feedback:347 execution begin
Feedback:404 validation begin! ErrorEmail=2
Feedback:419 validation complete! ErrorEmail=2

I want the sequence to be the following instead: 我希望序列如下:

checks start!
validation begin! ErrorEmail=2        //this will update the ErrorEmail var.
validation complete! ErrorEmail=2
checks complete! ErrorEmail=2
execution begin

I have searched and tried all the techniques (async false/deferred/callbacks), but I can't seem to figure out what might have went wrong. 我已经搜索并尝试了所有技术(异步错误/延迟/回调),但我似乎无法弄清楚可能出现的问题。

My code is as below: 我的代码如下:

        var ErrorEmail = -1;
        $(function () {

            $('#User_Email').mailgun_validator({
                api_key: 'x',
                in_progress: validation_in_progress, // called when request is made to validator
                success: validation_success,         // called when validator has returned
                error: validation_error,           // called when an error reaching the validator has occured
            });

            $("#FeedbackForm").submit(function (event) {
                if($("#User_Email").val())
                {
                    check().done(function(){
                        console.log('execution begin');
                            if (ErrorEmail == 2) {
                            if (confirm('Are you sure this is the email you want to use?')) {
                                $(form).submit();
                            }
                        }
                        else if (ErrorEmail == 0)
                        {
                            $(form).submit();
                        }
                    });

                    event.preventDefault();
                }
                else
                {
                    console.log('no email');
                    event.preventDefault();
                }
            });
        });

        function check(callback) {
            var dfrd1 = $.Deferred();
            console.log('checks start!');
            dfrd1.resolve(
                $('#User_Email').mailgun_validator({
                    api_key: 'x',
                    in_progress: validation_in_progress, // called when request is made to validator
                    success: validation_success,         // called when validator has returned
                    error: validation_error,           // called when an error reaching the validator has occured
                }).done()
            );

            console.log('checks complete! ErrorEmail='+ErrorEmail);
            return dfrd1.done().promise();
        }

        // while the lookup is performing
        function validation_in_progress() {
            $('#status').html("<img src=@Url.Content(@"~/Assets/img/loading.gif") height='16'/>");
        }

        // if email successfully validated
        function validation_success(data) {
            //var dfrd1 = $.Deferred();
            //dfrd1.resolve(data);

            console.log('validation begin! ErrorEmail=' + ErrorEmail);
            $('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));

            if (data['is_valid'] && !data['did_you_mean']) {
                ErrorEmail = 0;
            }
            else if (data['is_valid'] && data['did_you_mean']) {
                ErrorEmail = 2;
            }
            else
                ErrorEmail = 1;
            console.log('validation complete! ErrorEmail=' + ErrorEmail);

            //return dfrd1.promise();
        }

        // if email is invalid
        function validation_error(error_message) {
            $('#status').html(error_message);
        }

        // suggest a valid email
        function get_suggestion_str(is_valid, alternate) {
            if (is_valid) {
                ErrorEmail = 0;
                var result = '<span class="success">Address is valid.</span>';
                if (alternate) {
                    result += '<span class="warning"> (Though did you mean <em>' + alternate + '</em>?)</span>';
                    ErrorEmail = 2;
                }
                return result
            } else if (alternate) {
                ErrorEmail = 1;
                return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
            } else {
                ErrorEmail = 1;
                return '<span class="error">Email address is invalid. Please try another.</span>';
            }
        }

check() function already has a deferred object ( $('#User_Email').mailgun_validator ) the only thing to do is .pipe result of that function and call resolve function of dfrdl and in the end return dfrdl ONLY like below: check()函数已经有一个deferred对象( $('#User_Email').mailgun_validator )唯一要做的就是该函数的.pipe结果和dfrdl调用resolve函数,最后只返回dfrdl,如下所示:

function check(callback) {
    var dfrd1 = $.Deferred();
    console.log('checks start!');
    $('#User_Email').mailgun_validator({
            api_key: 'x',
            in_progress: validation_in_progress, // called when request is made to validator
            success: validation_success,         // called when validator has returned
            error: validation_error,           // called when an error reaching the validator has occured
        }).pipe(function(res){
            dfrd1.resolve(res);
        })

    console.log('checks complete! ErrorEmail='+ErrorEmail);
    return dfrd1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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