Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Promise<Doc | AsyncIterableIterator<Doc>> ? #4

Open
hayd opened this issue Dec 8, 2019 · 5 comments · May be fixed by #17
Open

How to use Promise<Doc | AsyncIterableIterator<Doc>> ? #4

hayd opened this issue Dec 8, 2019 · 5 comments · May be fixed by #17

Comments

@hayd
Copy link
Contributor

hayd commented Dec 8, 2019

Is there a better way to consume Promise<Doc | AsyncIterableIterator<Doc>>

What I was doing seems very hacky:
https://github.com/hayd/deno-lambda/blob/1ec6178894eba338da24702845baef5c23dc8139/example/api/candidate.ts#L52-L59

Is there a way to use discriminated unions ?

Perhaps it'd be better if these always returned Promise<AsyncIterableIterator<Doc>> ?

@chiefbiiko
Copy link
Owner

Yea I agree
Probly makes sense to have scan and query always return an async iterator

@chiefbiiko
Copy link
Owner

@hayd sorry for the late late response

unfortunately, always returning an async iterator does not really make sense -
the scan and query ops can return a single or multiple pages - details here

however, to answer your question I would test for the async iterator symbol:

if (result.hasOwnProperty(Symbol.asyncIterator)) {
  for await (const page of result) {/* handle page.Items */}
} else {
  /* handle result.Items */
}

@hayd
Copy link
Contributor Author

hayd commented Feb 24, 2020

Will the above work with 0.34.0 / strict mode?

If the op returns single page couldn't you wrap it to make this case into an asyncIterator ?

I think it would be much nicer to do this in library code rather than user code... since almost always the handling of page.Items will be the same as result.Items.

@hayd
Copy link
Contributor Author

hayd commented Mar 1, 2020

Something like the following could ensure it's always AsyncIterable<Doc>:

async function *toAsyncIterable(res: Doc | AsyncIterable<Doc>): AsyncIterable<Doc> {
  if (res.hasOwnProperty(Symbol.asyncIterator)) {
    // @ts-ignore
    for await (const r of res) {
      yield r
    }
  } else {
    yield res
  }
}

(not sure how to avoid the @ts-ignore...)

@wperron
Copy link

wperron commented Oct 28, 2020

Hey all, reviving this issue a bit; What I find myself missing when using this lib are the typings provided by the official lib, they're just very comprehensive and explicit. What do you feel about using those typings, or taking inspiration from them?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants