Skip to content

how to wait for async operations inside iterator of: Stream.reduce #707

@adrian-gierakowski

Description

@adrian-gierakowski

When consuming a stream with .reduce, I'd like to be able to do some async operations inside the iterator/reducer function and have the stream wait for their completion before consuming next element.

Here's what I'm doing right now:

const H = require('highland')
const Promise = require('aigle')

const reducer = async (memoPromise, x) => {
  console.log('got x:', x)
  const memo = await memoPromise
  console.log('processing x:', x)
  return Promise.delay(10).then(() => memo + x)
}

H([1, 2, 3])
  .reduce(reducer, 0)
  .toPromise(Promise)
  .then(console.log)

However the stream is being consumed as fast as possible, without waiting for async operation inside the reducer to complete. The output of running the above is:

got x: 1
got x: 2
got x: 3
processing x: 1
processing x: 2
processing x: 3
6

while I'd like it to be:

got x: 1
processing x: 1
got x: 2
processing x: 2
got x: 3
processing x: 3
6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions