我在节点服务器中处理了以下HTTP请求。我必须发回一个磁盘列表作为回复。
代码是:
DiskPromise.getDiskCount(client).then(function (diskCount) { DiskPromise.getDisks(client, diskCount).then(function (disks) { RaidPromise.getRaidCount(client).then(function (raidCount) { RaidPromise.getRaidArrays(client, raidCount).then(function (raidArrays) { for (i in disks) { disks[i].setRaidInfo(raidArrays); } RaidPromise.getGlobalSpareList(client).then (function(spareNames) { for (i in disks) { disks[i].setSpareNess(spareNames); } res.json(disks); }, function (err) { console.log("something (either getDiskCount, or one of the getDisk calls) blew up", err); res.send(403, { error: err.toString() }); }); }); }); }); });
承诺是SOAP调用。客户端需要4.5到7.0秒的时间才能获得响应。
我是否在做一些结构错误的布局代码?
答案 0 :(得分:2)
分析代码意味着获取磁盘,raidArrays和备用名称的平凡并行化机会。性能大大提高
var disks = DiskPromise.getDiskCount(client).then(function (diskCount) {
return DiskPromise.getDisks(client, diskCount);
});
var raidArrays = RaidPromise.getRaidCount(client).then(function (raidCount) {
return RaidPromise.getRaidArrays(client, raidCount);
});
var spareNames = RaidPromise.getGlobalSpareList(client);
Promise.all([disks, raidArays, spareNames]).spread(function(disks, raidArrays, spareNames) {
for(var i in disks) {
disks[i].setRaidInfo(raidArrays);
disks[i].setSpareNess(spareNames);
}
res.json(disks);
}).catch(function(err) {
console.log("something (either getDiskCount, or one of the getDisk calls) blew up", err);
res.send(403, { error: err.toString() });
});