astuyve / lambda-stream

Implements AWS Lambda Response Streaming in TypeScript for local development and testing
84 stars 10 forks source link

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

Closed bradsk88 closed 3 months ago

bradsk88 commented 8 months ago

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)
}

:point_up: 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.

astuyve commented 3 months ago

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