简体   繁体   中英

jQuery Promises and Deferred, confusion

I thought I'd finally got my head around promises but it seems I'm straying a little.

Can anyone put me out of my misery and explain what I'm doing wrong here:

t010 = { myGet: function(url) { var result = new $.Deferred(); result.resolve(ajaxRequest(url)); } }

Which is then called by my main method as so:

$.when(t010.myGet(seatId), t010.myGet(roomId)).then(function(d1, d2) { console.log(d1); }

I just console log undefined every time.

I think what i'm trying to achieve is fairly obvious, I want to call myGet twice and when both are complete do something with the results.

Thanks all!

You have to return the promise to use $.when

t010 = {
  myGet: function(url) {
    var result = new $.Deferred();
    result.resolve(ajaxRequest(url));

    return resolve.promise();
  }
}

but that resolves the promise immediately, passing back the result of the ajaxRequest function, which is probably undefined at that time?
But, the ajaxRequest already looks like it returns a promise, you can return it directly

t010 = {
  myGet: function(url) {
    return ajaxRequest(url));
  }
}

assuming your ajax function looks something like

function ajaxRequest(url) {

    return $.ajax({
        url : url
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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