Clever / wag

sWAGger - Web API Generator
Apache License 2.0
77 stars 6 forks source link

JS Client iterator: make forEach work with async functions #303

Closed aastein closed 4 years ago

aastein commented 4 years ago

Trying to do async tasks inside of a wag iter, like so, does not work

const someIter = someService.getSomeIter(params);

const f = async (data) => {
  await someService.doSomething(data);
}

await someIter.forEach(f);

because the implementation of someIter.forEach does not await calls to f.

This PR adds a new method called forEachAsync which will wait calls to f

the new way uses a for loop to preserve part of the behavior of forEach: arr.forEach(callback(currentValue [, index [, array]])[, thisArg]), which in addition to the current value, the index and entire result set are passed to f

johnhuangclever commented 4 years ago

Heads up, this does not technically match how forEach works on js arrays. It should not be blocking on async functions like for loops:

Playground Link

In this case it should be still possible to use iter.toArray and then for loop it there.

aastein commented 4 years ago

true, I don't like how js forEach works. I viewed this as an improvement because I wanted to be able to keep a small memory footprint when doing async work for each member of an array. Should we introduce a new method instead? I think having a simple interface to achieve doing async stuff mid-iter is something good to have.

Sayan- commented 4 years ago

Ohhh great call out john. asyncForEach or forEachAsync doesn't seem too crazy to me

aastein commented 4 years ago

sgtm! I'll make a new method for this n call it forEachAsync, so when people type forEa it will autocomplete / show both options if someone's autocomplete only works on prefixes.