SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
13.
问题:异步协作
var proxy = new EventProxy();
•
proxy.all("template", "data", "l10n", render);
嵌套还是并行?
$.get("template", function (template) {
// something
$.get("template", function (template) {
proxy.trigger("template", template);
}); // something
$.get("data", function (data) { {
$.get("data", function (data)
// something
// something
$.get("l10n", function (l10n) {
proxy.trigger("data", data);
}); // something
render(template, data);
$.get("l10n", function (l10n) {
});
// something
});
proxy.trigger("l10n", l10n);
});
});
13
14.
问题:异步还是同步
var proxy = new EventProxy();
var status = "ready";
• 复杂的异步编程
var _getFile = function (callback) {
proxy.once("template", callback);
if (status === "ready") {
fs.readFile("views/index.html", function (err, file) {
status = "pending";
proxy.fire("template", err, file);
});
}
};
var view = fs.readFileSync("../views/index.html", "utf8");
var _template;
var getTemplate = function (callback) {
if (_template) {
callback(null, _template);
} else {
同步 + 缓存,妥妥滴
_getFile(function (err, file) {
if (!err && !_template) {
_template = file.toString();
}
callback(null, _template);
});
}
};
14
15.
问题:缓存的使用
var map = {};
var get = function (key) {
var LimitableMap = require('limitablemap');
return map[key];
}; map = new LimitableMap(1000);
var
map.set("key1", "key1");
var set = function (key, value) {
map.get("key1");
map[key] = value;
};
// 检查缓存
if (!get(key)) {
// 从数据库或别的地方获取了对象后,放进缓存中
set(key, value);
}
15
17.
// 正确的方法
var chunks = [];
var size = 0;
问题:Buffer对象
res.on('data', function (chunk) {
chunks.push(chunk);
size += chunk.length;
});
var data = "";
res.on('end', function () {
res.on('data', function (chunk) {
var data = null;
//switch(chunks.length) {
// chunk是⼀一个Buffer对象
简单且正确的方法
data 0: data = new =隐藏的toString()
case += chunk;//Buffer(0);
var break;
bufferHelper new BufferHelper();
}) case 1: data = function
req.on("data",chunks[0]; (chunk) {
.on("end", function () {
bufferHelper.concat(chunk);
break;
})//对data转码
default:
.on('end',new Buffer(size);
}); data = function () {
for (var i = 0, pos = 0, l = chunks.length; i < l; i++) {
varvar chunk bufferHelper.toBuffer().toString();
html = = chunks[i];
}); chunk.copy(data, pos);
pos += chunk.length;
}
break;
}
}); 17