Marco Disco
Marco Disco

Reputation: 565

React Native Promises - They don't wait

I'm struggling again with promises, I don't understand or I'm expecting something else...

Really simple:

  const getImageRatio = () => {
    let res = Image.getSize(url, (w, h) => {
      console.log('width',w);
      return w / h;
    });
    return new Promise(resolve => resolve(res));
  };

I get correctly width

useEffect(() => {
    async function fetchData() {
      const fetcher = await getImageRatio();
      console.log('fetcher', fetcher);
    }
    fetchData();
  }, []);

but fetcher is undefined

I understood that the useEffect async is suppose to wait for the res or not? Where I'm mistaking?

codesandbox here: https://codesandbox.io/s/promise-problem-k2cgz

Upvotes: 2

Views: 223

Answers (1)

deadcoder0904
deadcoder0904

Reputation: 8683

The problem is you are always resolveing your promise even if it gets rejected. You have to resolve it when it actually resolves after getting width & height from the Image.getSize function.

Try replacing your getImageRatio function with the following:

const getImageRatio = () => {
  return new Promise((resolve, reject) => {
    Image.getSize(
      url,
      (width, height) => {
        resolve({ width, height });
      },
      (error) => reject(error)
    );
  });
};

Upvotes: 3

Related Questions