我想处理一系列数据,每个数据的输出都可以用作其他数据的输入。
例如:
var batch = [
{"id":"a1","depends":[],"data":{"some":"data a1"}},
{"id":"b1","depends":["a1"],"data":{"some":"data b1"}},
{"id":"b2","depends":["a1"],"data":{"some":"data b2"}},
{"id":"c1","depends":["b1","b2"],"data":{"some":"data c1"}},
{"id":"x1","depends":[],"data":{"some":"data x1"}},
];
这意味着一旦a1
完成,它的输出将被发送到b1
和b2
; 并且当这些完成时,它们的两个输出都将被发送到c1
(仅在它们都完成时。
x1
可以与所有a1
, b1
,b2
和c1
; 并行执行,并且b1
可以与 并行执行b2
,因为depends
它们之间没有定义。
c1
和完成后x1
,因此所有 5 个都完成后,应返回所有 5 个的输出。
我们将假设没有定义循环依赖,因此是有向无环图(DAG)
我想知道如何使用Q来实现它,因为:
- 所有数据的处理都是异步的,因此我需要使用回调,或者延迟和承诺;我更喜欢后者
- Promise 可以作为一种方便的方式来定义图中的边
但是,我无法通过概念阶段
var doPromises = {};
var doData = function(data, dependsResultsHash, callback) {
//Not real processing, simply echoes input after a delay for async simulation purposes
var out = {
echo: {
data: data,
dependsResultsHash: dependsResultsHash
}
};
setTimeout(function() {
callback(out);
}, 1000);
};
var doLine = function(id, depIds, data) {
var deferred = Q.defer;
var dependsPromises = [];
for (var i = 0; i < depIds.length; ++i) {
var depId = depIds[i];
dependPromise = doPromises[depId];
dependsPromises.push(dependPromise);
}
Q.all(dependsPromises).then(function(dependsResults) {
var dependsResultsHash = {};
for (var i = 0; i < depIds.length; ++i) {
var depId = depIds[i];
var depResult = dependsResults[i];
dependsResultsHash[depId] = depResult;
}
doData(data, dependsResultsHash, function(result) {
deferred.resolve(result);
});
});
return deferred.promise;
}
var doBatch = function(batch) {
var linePromises = [];
for (var i = 0; i < batch.length; ++i) {
var line = batch[i];
var linePromise = doLine(line.id, line.depends, line.data);
linePromises.push(linePromise);
doPromises[line.id] = linePromise;
}
Q.all(linePromises).then(function(lineResults) {
console.log(lineResults);
deferred.resolve(lineResults);
});
};
doBatch(batch);
(请注意,此代码未经测试,我不希望它起作用,只是为了说明我的问题所必需的要点。)
我想知道:
- 我这样做对吗?我是否完全错过了
Q
图书馆的重点。还是延期和承诺? 我主要关心的是
doData
功能:-- Is the way that I have selected the promises of the lines depended upon from the global list of promises `doPromises` ok? -- Is the way that I have obtained the results of the lines depended upon, and inpterpreted that OK?
具有以下
doBatch
功能:-- I have a local array for `linePromises` and an external hash for `doPromises`, and I feel that these should be combined. How can I do this correctly?
一般的
-- The code above presently assumes that all `deferred`s will eventually keep their `promise`s. What if they fail or throw an exception; how do I make my code more robust in handling this? -- I have used a closure allow acces to `doPromises` in both `doBatch` and `doLine`, and it seems a little odd here, is there a better way to do this?