0

I'm migrating a project written in TypeScript with AWS SDK v2 to v3.

This project has a method that fetches some DynamoDB records in a paginated way.

Looking at this example from AWS itself of how to make pagination in v3 of the SDK.

https://aws.amazon.com/blogs/developer/pagination-using-async-iterators-in-modular-aws-sdk-for-javascript/

The example says that in v3, paging is done using Async Iterators.

What I'm not able to understand, is that if I wrap the example code in a function, due to the use of Async/await TypeScript says that my function has to return a Promise. But in the example code I already have the list with records.

import {
  DynamoDBClient,
  paginateListTables,
} from "@aws-sdk/client-dynamodb";


async function getTableNames(): string[]  { // TypeScript says return has to be a Promise instead of string array

    const paginatorConfig = {
        client: new DynamoDBClient({}),
        pageSize: 25
    };

    const commandParams = {};
    const paginator = paginateListTables(paginatorConfig, commandParams);

    const tableNames: string[]  = [];
    // Because of await my function has to be asynchronous
    for await (const page of paginator) {
        tableNames.push(...page.TableNames);
    }

    // But I don't return a promise, I return the list already with the records
    return tableNames;
}


// Again due to the use of Async/Await I need to return a Promise
async function doSomething() {
    const tableNames = await getTableNames();
}

How and why should I return promise in getTableNames? Should I return a new Promise?

sartoz
  • 175
  • 1
  • 9
  • 1
    Just leave off the `: string[]`. Yes, an async function must always return a Promise – CertainPerformance Aug 19 '22 at 03:19
  • Or use `Promise` instead – qrsngky Aug 19 '22 at 03:21
  • I use `Promise` even though the code doesn't explicitly return a promise ? This is confusing – sartoz Aug 19 '22 at 03:23
  • 1
    Whatever you return in the body of an `async function`, the actual return type is always converted to Promise anyway. If you use `let x = getTableNames()` then the type of x is `Promise`. So, `async function getTableNames(): Promise ...` is properly typed. – qrsngky Aug 19 '22 at 03:25
  • Simpler example: `async function foo(): Promise { return ['a', 'b']; }` is valid typescript – qrsngky Aug 19 '22 at 03:32

0 Answers0