3

processImage() is a function that processes an image asynchronously.

uploadImage() is a function that uploads an image asynchronously.

Both of them return Promises.

sizes is array of length 4.

The image should be uploaded only after it is processed. Uploading and processing of a single size cannot happen in parallel.

What I want to do is to start all the 4 process/upload jobs immediately one after the other and have them execute asynchronously together. Once all 4 are complete, I execute some other code.

Since I'm passing an async function as a parameter to map, will the await keyword in it pause the execution until the processing/uploading of the first image is complete? In which case, this becomes a synchronous execution. I do not understand what exactly is happening here. If this code is indeed synchronous, how do I make it asynchronous?

var responses = await Promise.all(sizes.map(async function (size) {
        let processedBuffer = await processImage(buffer, size);
        let response = await uploadImage(processedBuffer.toString('base64'));
        return response;
    }));

//some other code

2 Answers 2

1

You code is asynchronous. You can easily check it by yourself.

const mockAsyncFn = () =>
    new Promise(resolve => setTimeout(() => resolve(), 2000));

const someAsync = async () => {
    const from = new Date();
    await Promise.all(
        [mockAsyncFn, mockAsyncFn].map(async fn => await fn())
    );
    const to = new Date();
    return to - from;
};

(async () => console.log(await someAsync()))();

Result will be ~2s but not 4.

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

2 Comments

Thank you. I executed this snippet and inferred that it is indeed asynchronous. Could you explain why it is, though? Why doesn't the second mockAsync() function wait for the first one to finish?
Promise.all runs array of async functions and waits until all of them will be resolved or one of them will be rejected.
1

async is syntactical sugar for a function returning a promise.

Consider this simple example:

async function ret42() {
   return 42;
}

This is equivalent to:

function ret42() {
   return Promise.resolve(42);
}

Under this point of view, async functions inside a callback are synchronous, until you meet an await (which is syntactical sugar for .then(() => ).

If you want every function to reach the end in order to execute the next one, you have to use for await, or just:

for (const fn of sizes) {
  await fn();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.