jQuery的推迟异步函数 [英] Jquery Deferred for an async function
问题描述
我一直在阅读了很多关于 jQuery的
延迟
对象。我可以看到它是如何工作进行去耦code。我写了使用Async.js这orignally,但会被建议使用的承诺。
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.
大多数的例子,我觉得只是链条的事情 AJAX
调用。我想链中的异步功能,但无法弄清楚如何做到这一点。我从数据库中检索一个时间,然后使用时间作为参数的URL,最后我再想做一个 AJAX
电话。
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.
这是我在哪里:
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
推荐答案
因为你通过 getLastImportTime
函数在
helper方法,它应该明确地返回一个诺
,(但 getLastImportTime()
你正在返回什么和时()
期待你传递一个的诺的),否则助手会评估它作为即时解决(或拒绝)的承诺。
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.
这可以解释为什么它似乎在管的功能
之前执行getLastImportTime()
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();
};
这篇关于jQuery的推迟异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!