2015-04-28 115 views
4

我有一个定期从服务器获取数据的高地流。我需要在地图中进行数据库查找。我找不到在高地的任何变压器上做任何异步操作的情况。Async Map with Highland.js

回答

2

您可以使用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] 
}); 
1

使用.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); 
}); 

Fiddle here

并行

或用.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); 
}); 

Fiddle here