Typescript sequence of a Class methods - javascript

I got a typescript class with an attribute that contain some connection data that are the result of an ajax call, here's a snippet:
class User {
// ... other stuff (constructor, attributes, methods)
static data:{id:number; token:string} = {id: 0, token: ""};
connect() {
// Ajax Call
.done(function(e){
User.data.id = e.id;
User.data.token = e.token;
})
}
request() {
if(User.data.id == 0)
setTimeout(() => {
this.request();
}, 500);
else return '?id=' + User.data.id + '&token=' + User.data.token;
}
}
I tried to use connect() and subsequently request() but sometimes the request() function starts before ajax's answer. Now I'm trying to write the request() function with some waiting time and a sort of recursion. Unfortunately it doesn't work.. My goal is to call the request() function and obtain the string only when "id" and "token" are ready (not 0 and empty string). Any suggestion would be appreciated!
PS: I can't put the request() function inside the ajax callback: the two functions should be separated

The calling code should be combining the promises with then. connect() and request() should just return their promises. e.g. they "promise to return done when connected" and "promise to return the requested data". In the case of request, it does not need a deferred object or promise as it simply returns a value immediately.
JSFiddle example: http://jsfiddle.net/TrueBlueAussie/qcjrLv4k/3/
// Return a fake connection after 5 seconds
var connect = function (){
var def = $.Deferred();
setTimeout(function(){
def.resolve();
}, 5000);
return def.promise();
}
var request = function(){
return "?data=d";
}
and use like this:
connect().then(request).done(function(data){
alert(data);
});
So in your case, just return the ajax call result as a promise from connect():
connect() {
return $.ajax({[snipped]})
.done(function(e){
User.data.id = e.id;
User.data.token = e.token;
});
}
and request simply returns the string:
request() {
return '?id=' + User.data.id + '&token=' + User.data.token;
}
Another way to do it is to save the connect promise:
var promise = connect();
and use it whenever you want to get the request data:
promise.then(request).done(function(data){
alert(data);
});
A better way, if your request is dependent on a "connection", is to pass the connect promise to the request method as a required parameter:
request(connectionPromise){
return connectionPromise.then(function(){
return '?id=' + User.data.id + '&token=' + User.data.token;
});
};
and call with:
request(connect()).done(function(data){
alert(data);
});
Example using this approach here: http://jsfiddle.net/TrueBlueAussie/qcjrLv4k/4/
Final example (based on commented desire to reuse connection). Combine the previous answers like this:
1) Save the connection as a property of the object.
// Start the connection process and save the promise for re-use
var connectionPromise = connect();
2) Use the connection as a parameter to the requests (so they do not need to have knowledge of the external variable):
// Make a request, passing the connection promise
request(connectionPromise).done(function(data){
alert(data);
});
3) The request method does not change from the previous example:
request(connectionPromise){
return connectionPromise.then(function(){
return '?id=' + User.data.id + '&token=' + User.data.token;
});
};

Once you are in promise land you need to stay there (or use a callback):
class User {
// ... other stuff (constructor, attributes, methods)
static data: { id: number; token: string } = { id: 0, token: "" };
private connectedPromise;
connect() {
// Ajax Call
this.connectedPromise = something.done( function ( e ) {
User.data.id = e.id;
User.data.token = e.token;
})
}
request() {
this.connectedPromise.then( () => {
if ( User.data.id == 0 )
setTimeout( () => {
this.request();
}, 500 );
else return '?id=' + User.data.id + '&token=' + User.data.token;
})
}
}
Store the result of connect in a var on only execute request if connect has resolved.
PS the request function is bad (I haven't cleaned it up but removed the return) in that it is maybe async i.e. it either returns a value or does some async work. Better to be consistent and always be async.

Related

Perform a set of recursive HTTP GET calls, and wait for them all

I have a REST service, offering a list of 'Json' objects, and each object may potentially have a link for another resource of its own class. Starting with a particular one, I need to fetch them all, performing a recursive http call.
So I wrote:
var steps = [];
var recursiveLookup = function(processId) {
return $.ajax({
url: SERVER_URL + processId,
success: function (activity) {
// Activity has a set of json objects called steps
var rtn = activity.path.map(step => {
if (step.type != "Node") {
steps.push(step);
} else {
return recursiveLookup(step.subProcessIntanceId);
}
}).filter(a => a != undefined);
return rtn;
}
});
}
That would correctly load all objects into the global steps var.
I need to be sure the method has finished, so I wrote:
var promises = recursiveLookup(processId);
Promise.all(promises).then(function () {
console.log(steps);
});
But it's not working, as the 'recursiveLookup' is returning the promise of $.ajax, instead of the set of promises pretended to be returned with the success method.
Furthermore, is it possible to get the steps as a returned value from the 'recursiveLookup' method instead, of using it as a global variable?
Nested recursion is not within my confort zone but maybe this will work:
var recursiveLookup = function(processId,steps=[]) {
return $.ajax({
url: SERVER_URL + processId,
})
.then(
function (activity) {
// Activity has a set of json objects called steps
steps = steps.concat(
activity.path.filter(
step => step.type !== "Node"
)
);
return Promise.all(
activity.path.filter(
step => step.type === "Node"
)
.map(
step=>
recursiveLookup(step.subProcessIntanceId,steps)
)
).then(
result=>steps.concat(result)
)
}
);
}
For tail call optimization to work the last thing the function does should be to call the recursive function but I think in promise chains it doesn't matter too much.
You should not use the success parameter if you want to work with promises. Instead, you want to return a promise, and you want to use then to transform the results of a promise into something different, possibly even another promise.
function request(page) {
…
// return the AJAX promise
return $.ajax({
url: '/echo/json/',
method: 'POST',
dataType: 'json',
data: {
delay: 1,
json: JSON.stringify(ret)
}
});
}
function requestOddsFrom(page, items) {
return request(page).then(function(data){
if (data.currentPage > data.totalPage) {
return items;
} else {
var filtered = data.items.filter(function(el){ return el%2 == 1; });
return requestOddsFrom(data.currentPage + 1, items.concat(filtered));
}
});
}
function requestAll(){
return requestOddsFrom(1, []);
}
requestAll().then(function(items) {
console.dir(items);
});
for more info jQuery Recursive AJAX Call Promise
How do I return the response from an asynchronous call?

More JQuery/Ajax and when/done/promise confusion

Once again I struggle with ajax calls - this time around some chaining issue. Overall here is what I need to accomplish:
I loop over some array, and for each item in the array, I need to do the following:
Issue an Ajax call, and upon success, I need to issue three other calls, which must be chained, so they run in sequence.
When all the items in the array have both their main call and the three chained subcalls completed, I must be able to do some action.
My problem is, that the program does not wait for the three chained subcalls to complete. In the code below, this can be seen by the "Done" statement in the log turns up before the subcalls have completed.
I have created a JSFiddle here: https://jsfiddle.net/LeifFrederiksen/td534phz/1/
Note: I have two different function for the addAttachments function (addAttachments and addAttachmentsAlternative) - none of them works like they should.
var items = ["A","B"];
save();
function doneSaving() {
log("<H1>Done</H1>");
}
function save() {
// Save all items, and do something when all is done...
log("<H1>Save initiated</H1>");
var returnValue = saveItems();
$.when(returnValue).done(function() {
doneSaving();
})
}
function saveItems() {
// Loop through all items and save each of them...
var requests = Array();
// Build array of requests to wait for...
for (item of items) {
requests.push(saveOneItem(item));
}
var returnValue = $.when.apply($, requests).done(function() {
log("All requests completed");
})
return returnValue;
}
function saveOneItem(item) {
// Save one item...
return addListItem(item,addListItemSuccess,addListItemFailure);
}
function addListItem(item, successFunction, failureFunction) {
// The actual ajax that handles saving to database (actually Sharepoint via REST)...
log("addListItem on: " + item);
var returnValue =
$.ajax({
url: "/echo/json/",
data: {html: item,
delay: 1},
}).done(function (data) {
if (successFunction != undefined) {
returnValue = successFunction(item, data); // Returns the newly created list item information
return returnValue;
}
}).fail(function (data) {
return failureFunction(item, data);
});
return returnValue;
}
function addListItemSuccess(item,data) {
log("addListItem succces - in succes function for " + item);
returnValue = addAttachmentsAlternative(item,data);
return returnValue;
}
function addAttachments(item,data) {
var attachment1Deferred = addListItem(item + "-attachment 1",addAttachmentSuccess,addAttachmentFailure);
var attachment2Deferred = attachment1Deferred.then(
function() {
return addListItem(item + "-attachment 2",addAttachmentSuccess,addAttachmentFailure);
});
var attachment3Deferred = attachment2Deferred.then(
function() {
return addListItem(item + "-attachment 3",addAttachmentSuccess,addAttachmentFailure);
});
attachment3Deferred.done(
function() {
log("Completed upload of all attachments for " + item);
})
return attachment3Deferred;
}
function addAttachmentsAlternative(item,data) {
return addListItem(item + "-attachment 1",addAttachmentSuccess,addAttachmentFailure)
.done(function(data) {
return addListItem(item + "-attachment 2",addAttachmentSuccess,addAttachmentFailure)
}).done(function(data) {
return addListItem(item + "-attachment 3",addAttachmentSuccess,addAttachmentFailure)
}).done(function(data) {
log("Completed alternative upload of all attachments for " + item);
});
}
function addAttachmentSuccess(item,data) {
log("addAttachment succces - in succes function for " + item);
var deferred = $.Deferred();
deferred.resolve();
return deferred;
}
function addListItemFailure(item,data) {
console.log("addListItem failed - calling failure function for " + item);
$("#console").append("<P>addListItem failed - in failure function for " + item);
}
function addAttachmentFailure(item,data) {
console.log("addListItem failed - calling failure function for " + item);
$("#console").append("<P>addListItem failed - in failure function for " + item);
}
function log(message) {
console.log(message);
$("#console").append("<P>" + message);
}
I am hoping to achieve some generic pattern that I can use in different cases.
I got my inspiration from this great article, but cannot get it to work in my scenario: https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.tu0sruz5k
Any ideas and inputs are more than welcome.
Regards
Leif
There are several issues with the provided example:
to chain the tasks of creating list items and adding attachments use
.then instead of .done. With .done callback that prints All requests completed it is fired once deferred (first ajax call in addListItem function) is getting resolved.
some functions like addListItem still uses callback function syntax, i would suggest convert them to promises
since all deferred are getting resolved in saveItems function there is no need to use jQuery.when() in save function
Modified demo

JavaScript Promises

Im trying to understand promises, but Im hitting a roadblock, I'm trying to query my Parse database for the last ran date object so that ill know when it was ran last. Then pass that date to the next function who can check my movie database for anything after the last time it was called. (I'm doing this to send out push notifications for new fields manually entered into Parse class) then actually send the push. But I'm not understanding the .then and promises, I'm new to JavaScript so any help would be appreciated!
Here is my code i have now.
Parse.Cloud.job("TestSendNewMoviePush", function(request, response) {
var query = new Parse.Query("MovieStatus");
var lastRunDateQuery = new Parse.Query("LastRun");
var lastRunDate;
var newDate;
var newCount = 0;
var installQuery = new Parse.Query(Parse.Installation);
query.greaterThan("updatedAt", lastRunDate);
query.equalTo("CurrentStatus", "Ready");
query.equalTo("imageStatusName", "Green");
installQuery.equalTo("role", "downloader");
lastRunDateQuery.get("d3WeNEwzIu", {
success: function(lastDateRanObj) {
console.log("Got the object " + lastDateRanObj);
var date = new lastDateRanObj.updatedAt;
lastRunDate = lastDateRanObj.updatedAt;
console.log(lastRunDate);
return lastRunDate;
},
error: function(lastDateRanObj, error) {
console.log("Failed to get object");
}
}).then(
query.count({
success: function(count) {
newCount = count;
return newCount
},
error: function(e) {
}
})).then(
Parse.Push.send({
where: installQuery,
data: {
"alert": newCount + " new movie(s) available!",
"badge": "Increment"
}
}, {
success: function() {
response.success("Success");
},
error: function(e) {
response.error("Error:" + e.code);
}
}));
});
lastRunDateQuery.get() returns a Promise object, which you can chain with a then, which itself is a function taking 2 functions as arguments: one that is called if the promise is resolved, and one that is called if the promise is rejected. You use these instead of the success and error parameters:
lastRunDateQuery.get()
.then(function(data) {
// success!!
}, function(error) {
// error :(
});
The functions you passed as arguments to then can themselves return promises, which you may subsequently chain with a then. In the example below I have omitted the error callbacks:
lastRunDateQuery.get()
.then(function(data) {
// data is the result of lastRunDateQuery.get()
return query.count();
})
.then(function(data) {
// data is the result of query.count()
return someOtherThing.someOtherMethodReturningAPromise();
});
.then(function(data) {
// data is the result of someOtherThing.someOtherMethodReturningAPromise()
});
And so on.
I would recommend having a look at the Promises/A+ spec - it's very instructive.
EDIT:
If the chaining concept is a bit confusing just think of it as a shorthand for the following:
var aPromise = lastRunDateQuery.get();
aPromise.then(
function() {}, // promise was resolved -> call this function
function() {}, // promise was rejected -> call this function
);

Multiple Promise Chains in Single Function

I have some code that will dynamically generate an AJAX request based off a scenario that I'm retrieving via an AJAX request to a server.
The idea is that:
A server provides a "Scenario" for me to generate an AJAX Request.
I generate an AJAX Request based off the Scenario.
I then repeat this process, over and over in a Loop.
I'm doing this with promises here: http://jsfiddle.net/3Lddzp9j/11/
However, I'm trying to edit the code above so I can handle an array of scenarios from the initial AJAX request.
IE:
{
"base": {
"frequency": "5000"
},
"endpoints": [
{
"method": "GET",
"type": "JSON",
"endPoint": "https://api.github.com/users/alvarengarichard",
"queryParams": {
"objectives": "objective1, objective2, objective3"
}
},
{
"method": "GET",
"type": "JSON",
"endPoint": "https://api.github.com/users/dkang",
"queryParams": {
"objectives": "objective1, objective2, objective3"
}
}
]
This seems like it would be straight forward, but the issue seems to be in the "waitForTimeout" function.
I'm unable to figure out how to run multiple promise chains. I have an array of promises in the "deferred" variable, but the chain only continues on the first one--despite being in a for loop.
Could anyone provide insight as to why this is? You can see where this is occuring here: http://jsfiddle.net/3Lddzp9j/10/
The main problems are that :
waitForTimeout isn't passing on all the instructions
even if waitForTimeout was fixed, then callApi isn't written to perform multiple ajax calls.
There's a number of other issues with the code.
you really need some data checking (and associated error handling) to ensure that expected components exist in the data.
mapToInstruction is an unnecessary step - you can map straight from data to ajax options - no need for an intermediate data transform.
waitForTimeout can be greatly simplified to a single promise, resolved by a single timeout.
synchronous functions in a promise chain don't need to return a promise - they can return a result or undefined.
Sticking with jQuery all through, you should end up with something like this :
var App = (function ($) {
// Gets the scenario from the API
// sugar for $.ajax with GET as method - NOTE: this returns a promise
var getScenario = function () {
console.log('Getting scenario ...');
return $.get('http://demo3858327.mockable.io/scenario2');
};
var checkData = function (data) {
if(!data.endpoints || !data.endpoints.length) {
return $.Deferred().reject('no endpoints').promise();
}
data.base = data.base || {};
data.base.frequency = data.base.frequency || 1000;//default value
};
var waitForTimeout = function(data) {
return $.Deferred(function(dfrd) {
setTimeout(function() {
dfrd.resolve(data.endpoints);
}, data.base.frequency);
}).promise();
};
var callApi = function(endpoints) {
console.log('Calling API with given instructions ...');
return $.when.apply(null, endpoints.map(ep) {
return $.ajax({
type: ep.method,
dataType: ep.type,
url: ep.endpoint
}).then(null, function(jqXHR, textStatus, errorThrown) {
return textStatus;
});
}).then(function() {
//convert arguments to an array of results
return $.map(arguments, function(arg) {
return arg[0];
});
});
};
var handleResults = function(results) {
// results is an array of data values/objects returned by the ajax calls.
console.log("Handling data ...");
...
};
// The 'run' method
var run = function() {
getScenario()
.then(checkData)
.then(waitForTimeout)
.then(callApi)
.then(handleResults)
.then(null, function(reason) {
console.error(reason);
})
.then(run);
};
return {
run : run
}
})(jQuery);
App.run();
This will stop on error but could be easily adapted to continue.
I'll try to answer your question using KrisKowal's q since I'm not very proficient with the promises generated by jQuery.
First of all I'm not sure whether you want to solve the array of promises in series or in parallel, in the solution proposed I resolved all of them in parallel :), to solve them in series I'd use Q's reduce
function getScenario() { ... }
function ajaxRequest(instruction) { ... }
function createPromisifiedInstruction(instruction) {
// delay with frequency, not sure why you want to do this :(
return Q.delay(instruction.frequency)
.then(function () {
return this.ajaxRequest(instruction);
});
}
function run() {
getScenario()
.then(function (data) {
var promises = [];
var instruction;
var i;
for (i = 0; i < data.endpoints.length; i += 1) {
instruction = {
method: data.endpoints[i].method,
type: data.endpoints[i].type,
endpoint: data.endpoints[i].endPoint,
frequency: data.base.frequency
};
promises.push(createPromisifiedInstruction(instruction));
}
// alternative Q.allSettled if all the promises don't need to
// be fulfilled (some of them might be rejected)
return Q.all(promises);
})
.then(function (instructionsResults) {
// instructions results is an array with the result of each
// promisified instruction
})
.then(run)
.done();
}
run();
Ok let me explain the solution above:
first of all assume that getScenario gets you the initial json you start with (actually returns a promise which is resolved with the json)
create the structure of each instruction
promisify each instruction, so that each one is actually a promise whose
resolution value will be the promise returned by ajaxRequest
ajaxRequest returns a promise whose resolution value is the result of the request, which also means that createPromisifiedInstruction resolution value will be the resolution value of ajaxRequest
Return a single promise with Q.all, what it actually does is fulfill itself when all the promises it was built with are resolved :), if one of them fails and you actually need to resolve the promise anyways use Q.allSettled
Do whatever you want with the resolution value of all the previous promises, note that instructionResults is an array holding the resolution value of each promise in the order they were declared
Reference: KrisKowal's Q
Try utilizing deferred.notify within setTimeout and Number(settings.frequency) * (1 + key) as setTimeout duration; msg at deferred.notify logged to console at deferred.progress callback , third function argument within .then following timeout
var App = (function ($) {
var getScenario = function () {
console.log("Getting scenario ...");
return $.get("http://demo3858327.mockable.io/scenario2");
};
var mapToInstruction = function (data) {
var res = $.map(data.endpoints, function(settings, key) {
return {
method:settings.method,
type:settings.type,
endpoint:settings.endPoint,
frequency:data.base.frequency
}
});
console.log("Instructions recieved:", res);
return res
};
var waitForTimeout = function(instruction) {
var res = $.when.apply(instruction,
$.map(instruction, function(settings, key) {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.notify("Waiting for "
+ settings.frequency
+ " ms")
.resolve(settings);
}, Number(settings.frequency) * (1 + key));
}).promise()
})
)
.then(function() {
return this
}, function(err) {
console.log("error", err)
}
, function(msg) {
console.log("\r\n" + msg + "\r\nat " + $.now() + "\r\n")
});
return res
};
var callApi = function(instruction) {
console.log("Calling API with given instructions ..."
, instruction);
var res = $.when.apply(instruction,
$.map(instruction, function(request, key) {
return request.then(function(settings) {
return $.ajax({
type: settings.method,
dataType: settings.type,
url: settings.endpoint
});
})
})
)
.then(function(data) {
return $.map(arguments, function(response, key) {
return response[0]
})
})
return res
};
var handleResults = function(data) {
console.log("Handling data ..."
, JSON.stringify(data, null, 4));
return data
};
var run = function() {
getScenario()
.then(mapToInstruction)
.then(waitForTimeout)
.then(callApi)
.then(handleResults)
.then(run);
};
return {
// This will expose only the run method
// but will keep all other functions private
run : run
}
})($);
// ... And start the app
App.run();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
jsfiddle http://jsfiddle.net/3Lddzp9j/13/
You have a return statement in the loop in your waitForTimeout function. This means that the function is going to return after the first iteration of the loop, and that is where you are going wrong.
You're also using the deferred antipattern and are using promises in places where you don't need them. You don't need to return a promise from a then handler unless there's something to await.
The key is that you need to map each of your instructions to a promise. Array#map is perfect for this. And please use a proper promise library, not jQuery promises (edit but if you absolutely must use jQuery promises...):
var App = (function ($) {
// Gets the scenario from the API
// NOTE: this returns a promise
var getScenario = function () {
console.log('Getting scenario ...');
return $.get('http://demo3858327.mockable.io/scenario');
};
// mapToInstructions is basically unnecessary. each instruction does
// not need its own timeout if they're all the same value, and you're not
// reshaping the original values in any significant way
// This wraps the setTimeout into a promise, again
// so we can chain it
var waitForTimeout = function(data) {
var d = $.Deferred();
setTimeout(function () {
d.resolve(data.endpoints);
}, data.base.frequency);
return d.promise();
};
var callApi = function(instruction) {
return $.ajax({
type: instruction.method,
dataType: instruction.type,
url: instruction.endPoint
});
};
// Final step: call the API from the
// provided instructions
var callApis = function(instructions) {
console.log(instructions);
console.log('Calling API with given instructions ...');
return $.when.apply($, instructions.map(callApi));
};
var handleResults = function() {
var data = Array.prototype.slice(arguments);
console.log("Handling data ...");
};
// The 'run' method
var run = function() {
getScenario()
.then(waitForTimeout)
.then(callApis)
.then(handleResults)
.then(run);
};
return {
run : run
}
})($);
App.run();

Why does my jQuery when().then() function trigger before the ajax request in when is done?

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..
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();
};
then it's easy to see what you've returned:
$.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);
});

Categories

Resources