Skip to content

Nodejs 18: Top Level Await using fetch API #13

@djsd123

Description

@djsd123

Hi there,

According to this blog-post top-level awaits should be fully supported. However, when I try this with the fetch API, I still have to use the await keyword within my handler function otherwise response.text() will be empty.

In short:
message: await response.text(),

vs

message: response.text(),

Am I misunderstanding something?

import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult} from 'aws-lambda'

const url = 'https://aws.amazon.com/'
// fetch API method is available from Nodejs 18
const response = await fetch(url)

export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    try {
        return {
            statusCode: response.status,
            body: JSON.stringify({
                message: await response.text(),    // <- HERE
                // input: event,
            }),
        }
    } catch (error) {
        console.log(error)
        return {
            statusCode: 500,
            body: JSON.stringify({message: error.body})
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions