I have been reading a lot about JQuery's deferred object. And I can see how it works to de-couple code. I wrote this orignally using Async.js but would was recommended to use promise.
Most examples I find just chain things to AJAX calls. I want to chain an async function but can’t figure out how to do it. I am retrieving a time from the database then using that time as a parameter in a url, finally I would then like to make a AJAX call.
This is where I’m at:
var fetch = function (contactId, callback, errorCallback)
{
var buildPromise = new $.Deferred();
var getLastImportTime = function ()
{
var querySuccess = function (tx, result)
{
buildPromise.resolve("7 oclock");
};
var queryError = function (tx, e)
{
buildPromise.reject("Error querying database");
};
database.open();
database.query("SELECT EventImportTime FROM Contact WHERE Contact.Id = ?", [contactId], querySuccess, queryError);
};
var buildUrl = function (lastImportTime)
{
console.log("I do happen");
var url = "http://";
url += 'MobileGetChangedEvents.aspx?Reference=';
url += '&LastImportTime=';
url += lastImportTime;
url += '&Format=JSON';
return url;
};
var makeRequest = function (url)
{
getJSON(url, callback, errorCallback)
};
$.when(getLastImportTime()).pipe(buildUrl).then(makeRequest);
Also my pipe methods seems to be called first :s
since you pass
getLastImportTimefunction towhenhelper method, it should explicitly return apromise, (but ingetLastImportTime()you are returning nothing andwhen()is expecting you to pass a promise) otherwise the helper could evaluate it as an immediate resolved (or rejected) promise.This could explain why it seems that function in
pipeis executed beforegetLastImportTime()So try to change your function like so