问题
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
回答1:
since you pass getLastImportTime
function to when
helper method, it should explicitly return a promise
, (but in getLastImportTime()
you are returning nothing and when()
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 pipe
is executed before getLastImportTime()
So try to change your function like so
var getLastImportTime = function () {
...
database.open();
database.query("SELECT ...");
return buildPromise.promise();
};
来源:https://stackoverflow.com/questions/10601030/jquery-deferred-for-an-async-function