React Native承诺--他们不需要等待。

问题描述 投票:2回答:1

我又在为承诺而苦恼,我不明白,或者说我在期待别的...

真的很简单。

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

我得到正确的 width

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

不过 fetcher is undefined

我明白 useEffect async 应该是等待 res我哪里弄错了?

这里是codesandbox.iospromis-problem-k2cgz。https:/codesandbox.iospromise-problem-k2cgz。

react-native
1个回答
3
投票

问题是你总是 resolve你的承诺,即使它得到 rejected. 你必须 resolve 当它真正解决后,得到 width &amp。heightImage.getSize 功能。

试着替换你的 getImageRatio 功能如下:

const getImageRatio = () => {
  return new Promise((resolve, reject) => {
    Image.getSize(
      url,
      (width, height) => {
        resolve({ width, height });
      },
      (error) => reject(error)
    );
  });
};
© www.soinside.com 2019 - 2024. All rights reserved.