简体   繁体   中英

Calling a function that returns a AsyncIterableIterator without using “for await” block

I'm writing an AWS Lambda function in TypeScript using the Node.js runtime. I'm using a "batchDelete" function from a DynamoDB ORM library which returns an AsyncIterableIterator type.

According to the documentation here https://github.com/awslabs/dynamodb-data-mapper-js#batchDelete , I should invoke the method with a for await loop like this:

for await (const found of mapper.batchDelete(toRemove)) {
    // items will be yielded as they are successfully removed
}

This all works great but the problem comes in where if I enable ESLint on my project. The default rules throw an error because the for await block is empty. I also get a warning because the found constant is never used. I have no use for the found constant and don't want to log it. I was wondering if there was another way to call an AsyncIterableIterator function where we disregard what is returned and don't have the empty block?

If you don't care about the results of the iteration, then you should probably just do something like this:

await Promise.all(toRemove.map(item => mapper.delete(item));

To use the mapper.batchDelete(toRemove) result more directly, you have to allow for multiple levels of promises. Perhaps you could do this:

await Promise.all(await mapper.batchDelete(toRemove)[Symbol.asyncIterator]());

In doing this, await mapper.batchDelete(toRemove)[Symbol.asyncIterator]() , that would get you the default async Iterator and then passing it to Promise.all() would iterate it to get an iterable of promises. Unfortunately, in building it to make this easier:

for await (const found of mapper.batchDelete(toRemove))

they made it a bit more difficult to just get an array of promises out of it.

FYI, here's a link to the code for the .batchDelete() method if you want to look at how it's implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM