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
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.