I need to set an async callback, because a function fetches content from a remote location. I'm doing this:
$.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();
});
with my when
function triggering a single Ajax request. In it's callback I'm returning an element to append to $(content)
.
My problem is, the then
function fires immediately and long before my ajax callback is run and returns something.
Question:
Is it not possible to use when()
with a function that makes an ajax-request? Do I have to make the ajax request directly in when()
? Or why is then()
triggered right away? How could I workaround this?
Thanks!
EDIT: My current version of the snippet:
$.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();
});
And the function, I'm calling (without content generation part):
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
}
};
When I console portable
inside my then
callback, I get the promise
object, so now the function is returning the promise vs an element. However when resolved, I was hoping I would get my fragment_container
when I'm not ... getting anything :-(
Hopefully clear enough.
Best advice I ever heard is to treat Async programming like normal functions and then add the promises at the end.
I'm having diffculty seeing where you are setting fragment_container, but here goes..
then it's easy to see what you've returned: