DEV Community

Discussion on: Then After forEach

Collapse
 
anduser96 profile image
Andrei Gatej

I've come up with this solution:

(async () => {
    const fetch = (name, time) => new Promise(resolve => setTimeout(resolve, time, name))
    const orders = [fetch('order1', 500), fetch('order2', 700), fetch('order3', 1000), fetch('order4', 1200)];

    orders[Symbol.asyncIterator] = async function * () {
        yield * [...this];
    }

    for await (const resolvedOrder of orders) {
        console.log(resolvedOrder)
    }

    console.log('finished !')
    /*
    order1
    order2
    order3
    order4
    finished!
    */
})()

I wouldn't say your approach is not optimized, it looks fine to me. I have to mention that I'm not very experienced though, so I'm not sure my opinion is 100% accurate.

I hope this was helpful to you in some way.