使用highland.js与原始流数据的引用串行执行异步任务 [英] Using highland.js to perform async tasks in series with references to original stream data
问题描述
我有一系列事件:
var eventStream = _([{
id: 1, foo: 'bar'
}, {
id: 2, foo: 'baz'
}]);
对于流中的每个事件,我需要加载一个模型实例(我的DAL返回promises)然后在模型的每个实例上调用一个方法,将原始事件数据中的一些数据作为参数传递。
For each event in the stream I need to load an instance of a model (my DAL returns promises) and then call a method on each instance of the model, passing some data from the original event data as an argument.
加载模型的实例并不太困难:
Loading instances of the model was not too difficult:
eventStream.map(function(data) {
return getModelPromise(data.id);
}).map(_).merge(); // result is a stream of model instances
但是一旦我拥有模型,我就无法想象如何在模型上调用方法并将 data.foo
传递给它。基本上,对于我需要做的每个实例:
But once I have the model, I can't figure out how to invoke a method on the model and pass data.foo
to it. Basically, for each instance I need to do:
modelInstance.doStuff(data.foo);
我玩过分叉流,拉叉上的模型然后使用 zip
和以不同的组合调用
,但我没有运气。有了异步,我会通过适当的闭包用户来处理这个问题。如何使用highland.js来实现这一点?
I've played with forking the stream, pulling models on the fork and then using zip
and invoke
in different combinations, but I haven't had any luck. With async I would have handled this pretty simply through proper user of closures. How can I accomplish this with streams using highland.js?
推荐答案
最简单的事情可能是将getModelPromise包装起来以便它返回一个承诺解析一个对象与您的模型和您的数据作为属性而不仅仅是您的模型。
Simplest thing to do might be to wrap getModelPromise so that it returns a promise resolving to an object with your model and your data as properties instead of just your model.
或者,如果您不想使用承诺,您可以做它在Highland:
Or, if you don't want to use a promise you can do it in Highland:
var modelStream = eventStream.map(function (data) {
return _(getModelPromise(data.id)).map(function (model) {
return {data: data, model: model};
});
}).parallel(10);
// then...
modelStream.map(function (x) {
x.model.doStuff(x.data.foo);
});
压缩modelStream和eventStream的观察版本也应该有效,但我通常更喜欢传递包含您需要的所有物品的对象。
Zipping the modelStream and an observed version of the eventStream should also work, but I usually prefer to pass around objects which contain everything you need.
这篇关于使用highland.js与原始流数据的引用串行执行异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!