为什么我的jQuery when()。then()函数在ajax请求完成之前触发?

我需要设置异步回调,因为函数从远程位置获取内容。 我这样做:

$.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(late) { console.log("done"); console.log(late) console.log($(content)) $(content).append(late).enhanceWithin(); }); 

使用my when函数触发单个Ajax请求。 在它的回调中,我正在返回一个元素以附加到$(content)

我的问题是, then函数在我的ajax回调运行之前很久then触发并返回一些东西。

问题
是否无法使用带有ajax请求的函数的when() ? 我是否必须在when()直接发出ajax请求? 或者为什么then()马上触发? 我怎么能解决这个问题?

谢谢!

编辑:我当前版本的代码段:

 $.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(fragment) { // DOM manip... console.log("NOW WE ARE DONE WITH WHEN"); console.log(fragment) $(content).append(fragment).enhanceWithin(); }); 

而函数,我正在调用(没有内容生成部分):

 priv.constructListbox = function (element, internal) { var no_data_body, no_data_cell, portable, gadget_id = element.getAttribute("data-gadget-id") || internal, settings = priv.gadget_properties[gadget_id], portal_type = settings.portal_type_title, // wrapper $parent = $(element.parentNode); if (settings !== undefined) { // ASYNC > this will trigger an Ajax request portable = priv.erp5.allDocs({ "query": "type: \"" + settings.datasource + "\"", "limit": [0, (settings.configuration.pagination.items_per_page_select[0] || 30)], "wildcard_character": "%", "include_docs": true }).always(function (answer) { .... stuff ... // finish // return to calling function if (internal) { console.log("foo"); console.log("no we only give back a fragment"); return fragment_container; } $parent.empty().append( fragment_container ).enhanceWithin(); }); // if internal call, return the promise object if (internal) { console.log("foo internal, promise"); return portable; } } else { // error handler } }; 

当我在我的回调中控制portable ,我得到了promise对象,所以现在函数返回了promise与元素。 然而,当我解决时,我希望我得到我的fragment_container当我不…得到任何东西:-(

希望足够清楚。

我听过的最好的建议是将Async编程视为普通函数,然后在最后添加promise。

我很难看到你在哪里设置fragment_container,但是这里有..

 priv.constructListbox = function (element, internal) { var dfd = new $.Deferred(); ... if (settings !== undefined) { portable = priv.erp5.allDocs({ "query": "type: \"" + settings.datasource + "\"", "limit": [0, (settings.configuration.pagination.items_per_page_select[0] || 30)], "wildcard_character": "%", "include_docs": true }).always(function (answer) { .... stuff ... // finish // return to calling function if (internal) { console.log("foo"); console.log("no we only give back a fragment"); dfd.resolve({message:"You did it!", element: fragment_container }); } $parent.empty().append( fragment_container ).enhanceWithin(); }); } else { dfd.reject({result:"Nope - no data came out"}); // error handler } return dfd.promise(); }; 

然后很容易看到你的回报:

 $.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(fragment) { console.log("NOW WE ARE DONE WITH WHEN"); console.log(fragment); }, function(fragment) { console.log("It failed"); console.log(fragment); });