Correction in Async chapter

I was just going through the Async chapter again and in one code sample, I think I noticed two mistakes. In the section about the flatten operator, this code is shown:

static func save(_ users: [User], request: Request) 
  -> [Future<HTTPStatus>] {
  let userSaveResults: [Future<User>] = []

  for user in users {
    userSaveResults.append(user.save())
  }

  return userSaveResults
    .flatten(on: request)
    .transform(to: HTTPStatus.created)
}

I think the return type of the function should be Future<HTTPStatus>, not [Future<HTTPStatus>] as yes, you’ll get a lot of future results, but will flatten them all into one Future<[Message]> which then gets transformed/discarded into Future<HTTPStatus>.

Furthermore, I think userSaveResults should be defined as a variable, not constant.

Please let me know if I’m wrong and/or I misunderstood the code.

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@cellane sorry I must have missed this! Yep both of those are errors, will fix them in the next release! Thanks!

No worries whatsoever!

By the way, a suggestion if I may: do you think it would be helpful to explain in the same chapter just a little bit how flatten works in the background? How many tasks from the array of Futures may run at once (I think it’d be determined by the number of CPU cores?) and if they’re run synchronously (no, that’s what syncFlatten is for, where Vapor will wait for each Future to finish before moving on to next one).

Alternatively, what about having a mini-chapter that would go over some of the less-often used, yet still useful operators? Such as syncFlatten, and and probably a few more that I even haven’t discovered.

I’ll look at expanding the async options, and good idea to explain them a bit! I’ll see what I can add

1 Like