Highland.js 的异步地图
Async Map with Highland.js
我有一个定期从服务器获取数据的 Highland 流。我需要在地图内部进行数据库查找。我找不到任何提及在 Highland 的任何变形金刚中执行任何异步操作的内容。
您可以使用 consume
以异步方式处理流。
_([1, 2, 3, 4]).consume(function(err, item, push, next) {
// Do fancy async thing
setImmediate(function() {
// Push the number onto the new stream
push(null, item);
// Consume the next item
next();
});
})).toArray(function(items) {
console.log(items); // [1, 2, 3, 4]
});
使用 .map
后,您可以使用 .sequence
作为:
var delay = _.wrapCallback(function delay(num, cb){
setTimeout(function(){ cb(null, num+1); }, 1000);
});
_([1,2,3,4,5]).map(function(num){
return delay(num);
}).sequence().toArray(function(arr){ // runs one by one here
console.log("Got xs!", arr);
});
或与.parallel
并行:
var delay = _.wrapCallback(function delay(num, cb){
setTimeout(function(){ cb(null, num+1); }, 1000);
});
_([1,2,3,4,5]).map(function(num){
console.log("got here", num);
return delay(num);
}).parallel(10).toArray(function(arr){ // 10 at a time
console.log("Got xs!", arr);
});
我有一个定期从服务器获取数据的 Highland 流。我需要在地图内部进行数据库查找。我找不到任何提及在 Highland 的任何变形金刚中执行任何异步操作的内容。
您可以使用 consume
以异步方式处理流。
_([1, 2, 3, 4]).consume(function(err, item, push, next) {
// Do fancy async thing
setImmediate(function() {
// Push the number onto the new stream
push(null, item);
// Consume the next item
next();
});
})).toArray(function(items) {
console.log(items); // [1, 2, 3, 4]
});
使用 .map
后,您可以使用 .sequence
作为:
var delay = _.wrapCallback(function delay(num, cb){
setTimeout(function(){ cb(null, num+1); }, 1000);
});
_([1,2,3,4,5]).map(function(num){
return delay(num);
}).sequence().toArray(function(arr){ // runs one by one here
console.log("Got xs!", arr);
});
或与.parallel
并行:
var delay = _.wrapCallback(function delay(num, cb){
setTimeout(function(){ cb(null, num+1); }, 1000);
});
_([1,2,3,4,5]).map(function(num){
console.log("got here", num);
return delay(num);
}).parallel(10).toArray(function(arr){ // 10 at a time
console.log("Got xs!", arr);
});