Home > Back-end >  Why my function return always _u 0 _v 0 _w null _x null?
Why my function return always _u 0 _v 0 _w null _x null?

Time:09-17

How can I return the value from an async function in React Native ? I am trying to compress images which was given by user.

Here is my compress function where compress each image

const compressFunction = async (item, format = SaveFormat.JPEG) => {
  const result = await manipulateAsync(
      item.uri,
      [],
      { compress: 0, format }
  )
  return result
};

Here is the function I try to call it. This is not working, console.log return Promise { _u 0, _v 0, _w null, _x null }. compressFunction is working and i can console.log and see the result for each return of "compressFunction(item)" but i can't see them in array list.

const compressImages = (items) => {
   const list = items.map( async (item) => ( await compressFunction(item)) )
   console.log(list)
}

But for example when i try to call like that it is working.

const compressImages = async (items) => {
   const list= await compressFunction(items[0])
   console.log(list)
}

I couldn't catch what im doing wrong, I'm working on it for hours. If someone can help me I would be grateful

CodePudding user response:

try await Promise.all(items.map(compressFunction))

Calling list.map(async function) will transform each element in list into a Promise.

Edit: if you make this much more verbose you can see what's going on here

const promises = items.map(item => {
  return new Promise((res) => {
    compressFunction(item).then(result => {
      return res(result);
    });
  });
});

// Now with the list of promises we have to use the Promise api
// to wait for them all to finish.
Promise.all(promises).then(results => {
  // do stuff with results
});

Async/await is just shorthand for this syntax

  • Related