Skip to content

Comments

Update README.md to emphasize async nature of response streaming#15

Merged
astuyve merged 1 commit intoastuyve:mainfrom
bradsk88:patch-1
Aug 19, 2024
Merged

Update README.md to emphasize async nature of response streaming#15
astuyve merged 1 commit intoastuyve:mainfrom
bradsk88:patch-1

Conversation

@bradsk88
Copy link
Contributor

@bradsk88 bradsk88 commented Mar 18, 2024

In the original example, the response stream was being filled before myHandler finished executing.

Since the non-AWS proxy in streamifyResponse awaits on the void promise returned by the provided handler, this means that the lambda would only output values that were fed into the stream imperatively during the scope of the handler function. Anything that happens asynchronously would not be captured.

For example:

import { APIGatewayProxyEventV2 } from 'aws-lambda'
import { streamifyResponse, ResponseStream } from 'lambda-stream'

export const handler = streamifyResponse(myHandler)

async function myHandler(
  event: APIGatewayProxyEventV2,
  responseStream: ResponseStream
): 
  console.log('Handler got event:', event)
  responseStream.setContentType('text/plain')
  responseStream.write('Hello')
  setTimeout(() => {
      responseStream.write('World')
      responseStream.end()
  }, 1000)
}

☝️ Here, we don't return a promise. So the response resolved by the lambda will simply be "Hello", because the proxy won't wait for the async write of "World".

The solution to this is to use a promise that only resolves once the potential asynchronous work has been completed. (See the proposed changes of this PR)

Might as well update the readme to direct people towards that.

In the original example, the response stream was being filled before `myHandler` finished executing. 

Since the non-AWS proxy in `streamifyResponse` awaits on the void promise returns by the provided handler, this means that the lambda would only output values that were fed into the stream imperatively inside the handler function.  Anything that happens asynchronously would not be captured.

The solution to this is to use a promise that only resolves once the potential asynchronous work has been completed.
@astuyve
Copy link
Owner

astuyve commented Aug 19, 2024

Yup, thanks. Sorry I missed this for so long, my notifications are a disaster.

@astuyve astuyve merged commit 2f680bc into astuyve:main Aug 19, 2024
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 this pull request may close these issues.

2 participants