Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
var foo = ajax('example.com');, а уж целое асинхроноое приложение — это просто ужас.// обработка у нас будет выглядеть как-то так:
new Topic(id).get(function (data) {
render(data.article, data.comments);
});
// Сам класс прост:
var Topic = function (conn, id) {
this.conn = conn;
this.id = id;
};
Topic.prototype = {
// Получены и статья и комменты:
get : function (fn) {
var data = {};
var set = function (key, value) {
data[key] = value;
if ('article' in data && 'comments' in data) fn(data);
};
this.getArticle(function (article) {
set('article', article);
});
this.getComments(function (comments) {
set('comments', comments);
});
},
// получение статьи из БД:
getArticle(fn) {
this.conn.query(qArticles, function (err, res) {
if (err) throw err;
res.fetchAll(function (err, rows) {
if (err) throw err;
fn(rows.length ? rows[0] || null);
});
});
},
// Получение комментов из БД:
getComments(fn) {
this.conn.query(qComments, function (err, res) {
if (err) throw err;
res.fetchAll(function (err, rows) {
if (err) throw err;
fn(rows);
});
});
},
};
(function() {
alert(1);
setTimeout(arguments.callee, 5000);
})();
(function() {
alert(2);
setTimeout(arguments.callee, 3000);
})();
Runnable task = new Runnable() {
public void run() {
while (true) {
try {
SwingUtils.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "1");
}
});
Thread.sleep(5000);
} catch (InterruptedException ex) {
break;
}
}
}
};
new Thread(task).start();
Как избавиться от пристрастия к синхронности