新在JavaScript异步编程。任何建议? [英] New to asynchronous programming in JavaScript. Any advice?
问题描述
异步回调是伟大的,但,当一个回调依赖于他人的结果,我有一个包含了回调,等API调用回调。
Asynchronous callbacks are great but when one callback depends on the result of another I have callbacks with api calls that have callbacks, and so on.
apiCall(function () { apiCall(function () { apiCall(function () ...
我能说出其中包括内嵌的回调函数。这看起来prettier和少筑巢,但我没有找到任何更容易阅读。
I can name the callback functions instead of including them inline. That looks prettier and has less nesting but I do not find it any easier to read.
下面是一个例子。我需要查询本地SQLite数据库,用结果来查询服务器,然后使用响应更新本地数据库。
Here is an example. I need to query the local sqlite database, use the result to query a server, then use the response to update the local database.
function sync() {
db.transaction(
function (transaction) {
execute(transaction, 'SELECT max(server_time) AS server_time FROM syncs;', [],
function (transaction, results) { // Query results callback
var t = results.rows.item(0).server_time;
$.post('sync.json', { last_sync_time: (t || '1980-01-01') },
function (data) { // Ajax callback
db.transaction(
function(transaction) {
$(data.thing).each(function () {
var thing = new Thing(this.thing);
thing.insert(transaction);
});
});
});
});
});
}
有没有办法来untagle本(除命名回调)?
Is there a way to untagle this (other than naming the callbacks)?
推荐答案
命名回调是一件事你可以做,但你需要做其他的事情是不重叠的SQL事务。 ( 1 )
Naming the callbacks is one thing you can do, but the other thing that you need to do is to have non-overlapping SQL transactions. (1)
您第一笔交易应该是这样的:
Your first transaction should be like this:
// The whole thing starts here
db.transaction(selectTimeCB, null, ajaxPost);
事务与回调开始选择的时间,并且当所述的交易的是完整的,使向ajaxPost动作的呼叫
The transaction starts with the callback to select the time, and when the transaction is complete, make a call to the ajaxPost operation.
// Initial transaction to get server_time
var selectTimeCB = function(t) {
var query = 'SELECT max(server_time) AS server_time FROM syncs';
t.executeSql(query, [], postLastSyncCB);
};
// This saves the results from the above select, and nothing else.
var server_time;
var postLastSyncCB = function(t, results) {
server_time = results.rows.item(0).server_time;
};
var ajaxPost = function() {
$.post('sync.json', { last_sync_time: (server_time || '1980-01-01') }, nextDbTransaction);
};
如果你有重叠的SQL事务,真正能够杀死对数据库的性能。我最近做了一个有点超过500行的数据库200混合交易测试,发现保持交易建立单独的减少超过90秒的运行时间为3-5秒。
If you have overlapped SQL transactions, that can really kill the performance of the database. I recently did a test of 200 mixed transactions on a database with a bit over 500 rows, and found that keeping the transactions separate reduced a run time of over 90 seconds to 3-5 seconds.
这篇关于新在JavaScript异步编程。任何建议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!