Donaldcwl / browser-image-compression

Image compression in web browser
MIT License
1.3k stars 160 forks source link

Async/await not working as expected #2

Closed pmourelle closed 5 years ago

pmourelle commented 6 years ago

Hi there. I'm trying to use browser-image-compression with async/await, not being able to do it. I wrapped the call to have it resolve by its own and having a cleaner code as below (showing relevant parts).

const myImageCompressor = async (val, maxSizeMB, maxWidthOrHeight) => {
  const result = await imageCompressor(val, maxSizeMB, maxWidthOrHeight);
  return result;
};

Then I'm using it as:

for (let item of Object.entries(payload)) {
  let [key, val] = item;
  ...
  const maxMB = 1,      // max MBs
  maxSize = 1200; // max Size rescale
  val = myImageCompressor(val, maxMB, maxSize);
  ...
}

Problem is that val doesn't have a File but a still unsolved Promise. Is this a bug or there's anything wrong in the code above?

kdalkafoukis commented 6 years ago

@pmourelle I think you miss await to val = myImageCompressor(val, maxMB, maxSize); Async/await works for me

Donaldcwl commented 5 years ago

@pmourelle @kdalkafoukis is right, your async function "myImageCompressor " return a promise which needs to be "await" for the result.

You may try:

Promise.all(Object.entries(payload).map(async (item) => {
  let [key, val] = item;
  ...
  const maxMB = 1,      // max MBs
  maxSize = 1200; // max Size rescale
  val = await myImageCompressor(val, maxMB, maxSize); 
  //or just: val = await imageCompressor(val, maxMB, maxSize);
  ...
})).then(successFn).catch(errorHandlerFn)
pmourelle commented 5 years ago

Thanks guys. I'd done some workaround on overall code. I'll try some clean up on this next week.