search

Home  >  Q&A  >  body text

javascript - Please tell me about the problem of changing jq's callback function to promise implementation

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.

漂亮男人漂亮男人2806 days ago719

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:43:59

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

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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:43:59

    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.

    reply
    0
  • Cancelreply