5

我有一个定期从服务器获取数据的 Highland 流。我需要在地图内进行数据库查找。我找不到任何提到在任何 Highland 的变形金刚中做任何异步的事情。

4

2 回答 2

3

您可以使用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]
});
于 2015-04-28T09:41:48.600 回答
1

使用 a 后,.map您可以将 a.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);
});

在这里提琴

于 2015-04-28T09:42:13.047 回答