我又在为承诺而苦恼,我不明白,或者说我在期待别的...
真的很简单。
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。
问题是你总是 resolve
你的承诺,即使它得到 reject
ed. 你必须 resolve
当它真正解决后,得到 width
&amp。height
从 Image.getSize
功能。
试着替换你的 getImageRatio
功能如下:
const getImageRatio = () => {
return new Promise((resolve, reject) => {
Image.getSize(
url,
(width, height) => {
resolve({ width, height });
},
(error) => reject(error)
);
});
};