0

So I know that async/await will not work with map. I am just returning my request and using Promise.all() to execute them. My question is that I have other promises inside and was wondering if the Promise.all() will also execute those inside the map in the correct order.

Here is the code:

const productImageIds = Object.keys(data.webImages)

        for(let i = productImageIds.length; i--;){
            const productId = productImageIds[i]
            const images = data.webImages[productId]
            const requests = images.map(async (image, i) => {
                const name = `${productId}_${i}.${image.split(`.`).pop()}`
                const imageStream = await downloadImage(image, name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
                const res =  sanityRequest({
                    ...sanityConfig,
                    type: `images`,
                    endpoint: `assets`,
                    contentType: `image/jpeg`,
                    body: imageStream,
                params: `?filename=${name}`,
                })


                    await unlinkSync(name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
                    return res

            })

            const uploadedImages = await Promise.all(requests)
        }
2
  • Concurrent Promises are never executed in a given order. Promise.all resolves when all Promises end, whatever their order. Commented Feb 14, 2020 at 14:03
  • 1
    Just a quick note. You might want to change for(let i = productImageIds.length; i--;){ to be for(let i = productImageIds.length-1; i--;){ to avoid accessing out of bounds. Commented Feb 14, 2020 at 14:04

1 Answer 1

4

My question is that I have other promises inside and was wondering if the Promise.all() will also execute those inside the map in the correct order.

No.

Promise.all() will create a promise which resolves when all the promises passed to it resolve. It has no influence over what order those promises resolve in (and couldn't because they will have started running before Promise.all is invoked).

If you want to deal with each value of images in sequence (rather than in parallel) then use a regular for loop.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.