3

我认为/希望我遗漏了有关 Promise 编程范式的一些东西。我在 jQuery 上运行以下代码,因为我想从URL_1获取数据然后(成功时)从URL_2获取data2。其他变量来自围绕这段代码的上下文。

但是,我得到的是两次URL_1 的数据!!

.ajax({
    url: URL_1,
    type: "GET",
    async: false,
    cache: false
}).then(function (data) {
    myObj = process(otherObj, data, URL_1);
    return $.ajax({
        url: URL_2,
        type: "GET",
        async: false,
        cache: false
    });
}).done(function (data2) {
    myObj2 = process_more(data2, URL_2, someObj);
    myCounter--;
    if (myCounter== 0) {
        console.log("%%%% COMPLETE %%%%");
    }
});

提前感谢您的宝贵时间!!

平底锅

4

2 回答 2

2

事实证明,只要 jQuery 版本大于 1.8(我知道但没有注意到我使用的是最后一个版本),代码就可以正常工作。我用最新版本替换了 jQuery,一切都按预期工作。然而,@Bergi 关于async:false无用甚至导致问题是正确的。

在早期版本的 jQuery 中,promise/deferred 模型是“损坏的”并且没有按预期工作/应该 wrt 原始 promise 模型(https://www.promisejs.org/)。

另见:http ://api.jquery.com/deferred.then/

于 2014-07-22T13:06:28.380 回答
0

我是这样解决的:

for (var i = 0; i < json.length; i++) {

    if(json[i].university_name !== '' && json[i].state_code !== ''){

        $.when(
            $.ajax({
                async: false,
                url: "validateUniversityExist.php",
                method: 'post',
                dataType: 'json',
                data:{
                    'name': json[i].university_name,
                    'state_code' : json[i].state_code
                }
            })).then(function( resp, textStatus, jqXHR ) {

                if(resp.id_university !== '' || resp.id_university !== undefined){

                    if (json[i].record_status == 3){

                        $.ajax({
                            url: "createNewBenefits.php",
                            method: 'post',
                            dataType: 'json',
                            data:{
                                'id_university': resp.id_university,
                                'state_code' : json[i].state_code,
                                'updated' : json[i].updated,
                                'id_visa' : json[i].visa_type,
                                'record_status' : json[i].record_status,
                                'mandatory' : json[i].mandatory,
                                'aca' : json[i].aca
                            }
                        }); // end insert complete record ajax

                    }

                }

            }); // end university when ajax
    }


} // end for

使用when和then。https://api.jquery.com/jquery.when/

于 2017-11-29T17:54:14.777 回答