问题描述
我有一系列简单的事件:
I have a simple chain of events:
- 从metaData表获取列(异步)
- 加载选定的列(异步)
- 渲染列表
我以前只是链接这些函数,每个函数完成后都会调用下一个.但是,发生的情况不是很明显(调用getColumnsFromMeta
会导致填充视图).因此,为了清晰起见和代码重用,我想使用JQuery
Promises
重构它们.我以前用过诺言.但是,如何链接两个以上? getColumnsFromMeta ().then(loadSourceFromDatabase /*some arguments*/) //.then(renderList)?;
I used to just the chain these functions, each calling the next when it had completed. However, its not very obvious what's going (calling getColumnsFromMeta
results in the view being populated). So in the interest of clarity and code re-use I'd like to refactor these using JQuery
Promises
. I have used promises before. But how do I chain more than two? getColumnsFromMeta ().then(loadSourceFromDatabase /*some arguments*/) //.then(renderList)?;
这是getColumnsFromMeta
的示例:
var getColumnsFromMeta = function(id)
{
var sql,
dfd;
dfd = $.Deferred();
var onSuccess = function(tx, result)
{
var columns = [];
for (var i = 0; i < result.rows.length; i++)
{
columns.push(result.rows.item(i).Column);
}
dfd.resolve(columns);
};
var onError = function(tx, error)
{
dfd.reject(error);
};
sql = "SELECT Column FROM Meta WHERE id = ?";
database.query(sql, [id], onSuccess, onError);
return dfd.promise();
};
推荐答案
应该是这样的:
function getColumnsFromMeta()
{
var d = $.Deferred();
// retrieve data in async manner and perform
// d.resolve(columns);
return d.promise();
}
function loadSelectedColumns(columns)
{
var d = $.Deferred();
// retrieve data in async manner and perform
// d.resolve(data);
return d.promise();
}
function render(data)
{
// render your data
}
getColumnsFromMeta().pipe(loadSelectedColumns).pipe(render);
http://jsfiddle.net/zerkms/xYDbm/1/-这是工作样本
http://joseoncode.com/2011 /09/26/a-walkthrough-jquery-deferred-and-promise/-这是我非常喜欢的关于Promise的文章
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ -- this is the article I really like about promises
这篇关于jQuery承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!