Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an async iterable to chain promises

Tags:

javascript

I have an array of items (projects) I want to upload, one by one in sequence.

I know how to do this by constructing a promise chain, but I wanted to try and use an async iterator and for...await.

First I map the projects to arrow functions which will, when called, invoke the upload; then I create an async iterable via an async generator function.

Then I use for...await to loop over the async iterable.

Is this an idiomatic approach?

For example, (p)=>()=>upload(p) looks strange to me, as does the IIFE (async function*() { for (let p of arr) yield p() }()).

const upload = ({name}) => 
    new Promise((resolve) => 
        setTimeout(() => resolve(`Response for upload of: ${name}`), 1000))

const asyncIter = (arr) => (async function*() { for (let i of arr) yield i() }())

const uploadInSeries = async (arr) => {
    const iter = asyncIter(arr.map((i) => () => upload(i)))
    for await(let response of iter) {
        console.log(response)
    }
}

const projects = [{ name: "P1" }, { name: "P2" }, { name: "P3" }]
uploadInSeries(projects)
like image 563
Ben Aston Avatar asked Oct 23 '25 19:10

Ben Aston


1 Answers

This is not a usecase for an async iterable. Async iterables only make sense if you don't know wether you have a next element or not. In your case however, the number of requests is already known, so you can just do

 for(const el of arr)
   await request(el);
like image 121
Jonas Wilms Avatar answered Oct 26 '25 08:10

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!