0

All, I have discovered iced-coffee-script today and was very happy to see that someone tried designing a more readable coffee-script dialect for async programming.

I can't get iced to work though with comprehensions like the map and reduce functions, or the more simply do/for. E.g. the output of...

square = (x, callback) ->
  setTimeout ->
      callback x * x
    , 5000

console.log [ 1..10 ].map (x) ->
  await square x, defer y
  y  

... is simply an array of undefineds! What am I missing? Thank you in advance.

Giacecco

giacecco
  • 661
  • 1
  • 5
  • 8

2 Answers2

1

I'm new to iced, but here's my understanding:

Using await and defer doesn't actually stop control flow, your function will return as usual. So .map is getting "undefined" returned for each element.

Here's the serial version, as above:

foo = []
for x in [ 1..10 ]
  await square x, defer y
  foo.push y

If you want to do it in parallel, it's like this:

foo = []
await
  for x,i in ([ 1..10 ])
    square x, defer foo[i]

Notice that I'm wrapping the [1..10] range in parentheses. This is so the range gets expanded to an array, so we can get the index inside the loop, explained here: https://github.com/jashkenas/coffee-script/issues/2586

.push wouldn't work here, because the callbacks generally aren't guaranteed to come back in the order you want.

There are plenty of other ways to go about doing this, but I think this is the most concise way to do what you are trying to do above. Note that if it's a big loop, it will allocate that whole array first, which might be inefficient.

doubledriscoll
  • 1,179
  • 3
  • 12
  • 21
0

I'll add my 2 cents to @doubledriscoll's answer so you can have better understanding of what is actually going on here. Let's just translate your code example into regular javascript, so this code:

console.log [ 1..10 ].map (x) ->
  await square x, defer y
  y  

Is equivalent of:

console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function(x) {
  return square(x, function(y) {
    return y;
  });
});

Which will print an array of things square function returns, which is undefined.

Andrew
  • 8,330
  • 11
  • 45
  • 78