jquery when/then (also when/done) not waiting

旧巷老猫 提交于 2019-11-30 06:58:00
function GetHours() {
    return $.ajax({
        ...
    });
};

$.ajax() returns a Promise. $.when() takes a collection of Promises, and returns a promise that completes when all the input promises complete .then() is a method on Promise (in this case, the wrapper Promise that when() created) that calls it's first function arg when the promise resolves with success.

so, your GetHours needs to return a Promise that when() can wrap, and you call the then() on. you could actually skip the when() part and just call .then on the return from GetHours.

you aren't getting an error because .when() also takes any old object, and if it doesn't implement the Promise interface, it just treats it like an already-completed Promise.

This is not be the OPs issue, but I had something similar happen and it was because I was calling $.when(...) incorrectly by passing an array of promises.

Per the documentation for jQuery.when if you want to wait for multiple Deferred objects you must make the call as such:

$.when( d1, d2 ).then(....);

That means that if you have multiple deferred objects in an array you should use apply(...), otherwise $.when will not work properly. So your call for an array of deferred objects would look like this:

$.when.apply(this, arrayOfDeferred).then(....);

Here is a JS Fiddle demonstrating this:

https://jsfiddle.net/Lvo4hrez/11/

You need to return the result of $.ajax from the GetHours function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!