当尝试获取图像的原始大小时,我从Async / Await函数返回了此{ _40: 0, _65: 0, _55: null, _72: null }
。有关功能用法,请参见https://www.npmjs.com/package/react-native-image-size。
这是我的代码。
getImgSize = async (url) => {
const {width, height} = await ImageSize.getSize(url);
const imgSize = { width: width, height: height }
console.log(imgSize) // result is { width: 950, height: 634 }
return imgSize;
}
function getImage(){
var imgSize = getImgSize("https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn");
console.log(imgSize) // result after returned { _40: 0, _65: 0, _55: null, _72: null }
}
我希望结果类似于{ width: 950, height: 634 }
,但是我提到的结果却被返回了。
答案 0 :(得分:1)
您正在调用async
函数,这意味着希望。您必须等待结果。
所以要么使用await
getImage = async () => {
var imgSize = await getImgSize("https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn");
console.log(imgSize);
}
或以这种方式处理
getImage = () => {
getImgSize('https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn').then((imgSize) => {
console.log(imgSize);
});
}
答案 1 :(得分:0)
您需要添加await
和async
函数:
getImgSize = async (url) => {
const {width, height} = await ImageSize.getSize(url);
const imgSize = { width: width, height: height }
console.log(imgSize) // result is { width: 950, height: 634 }
return imgSize;
}
async function getImage(){
var imgSize = await getImgSize("https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn");
console.log(imgSize) // result after returned { _40: 0, _65: 0, _55: null, _72: null }
}
答案 2 :(得分:-1)
您必须将async与await结合使用,或者对它使用then()=>进行查看,然后在需要等待的地方使用它。
答案 3 :(得分:-3)
尝试
getImgSize("<Image URL>")
.then((imgSize)=>console.log(imgSize))
或将其放入异步/等待状态
getImage = async () => {
var imgSize = await getImgSize("<Image URL>");
console.log(imgSize);
}