javascript - Please tell me about the problem of changing jq's callback function to promise implementation
漂亮男人
漂亮男人 2017-05-19 10:41:59
0
2
718

Code segment 1

var prepayment_apply,prepayment_operational;
// 
loadMain().then(loadBtn()).then(function () {
    console.log(prepayment_operational);  // undefined
    return loadProgress();
});

// fun1
function loadMain() {
    return $.ajax({
        url:'...',
        success:function (data) {
            prepayment_apply = data.prepayment_apply;
        }
    })
}

// fun2
function loadBtn() {
    return $.ajax({
            url:'...',
            success:function (data) {
                prepayment_operational = data.prepayment_operational;
            }
        })
}

// fun3
$.ajax({
    url:'...',
    type:'get',
    dataType:'json',
    load_animation:true,
    success:function (data) {
        ...
    }
})

When I encapsulate $.ajax into a function, the prepayment_operational typed using promise is undefined.

Code segment 2

var prepayment_apply,prepayment_operational;
// 
loadMain().then(function () {
                    $.ajax({
                        url: '...',
                        success: function (data) {
                            prepayment_operational = data.prepayment_operational;
                        }
                    })
                }
            )
          .then(function () {
                console.log(prepayment_operational);  // '111'
                return loadProgress();
            });

When I write ajax directly in then, I can get the value I want. And when I put the

in snippet 1
loadMain().then(loadBtn()).then(function () {
    console.log(prepayment_operational);  // undefined
    return loadProgress();
});

changed to

loadMain().then(function () {return loadBtn()}).then(function () {
    console.log(prepayment_operational);  // undefined
    return loadProgress();
});

Code segment 1 can also console out prepayment_operational normally.
I would like to ask why this is.

漂亮男人
漂亮男人

reply all(2)
phpcn_u1582

thenWhat you get should be a function, not anything else. . .

loadMain().then(loadBtn)....

给我你的怀抱

jQ itself has Promise (in the deferred module), such as:

$.ajax({
    url:'...',
    success:function (data) {
        prepayment_operational = data.prepayment_operational;
    }
});

This way of writing is traditional, and:

$.ajax({
    url:'...'
}).done(function (data) {
    prepayment_operational = data.prepayment_operational;
});

This uses jQ’s built-in Promise mechanism ($.ajax本身会返回Promise,可以挂.done()或者.fail())。也可以用.promise()Dynamicly returns the promise object.

Please refer to the "Delayed Object" in the jQ documentation for details.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template