You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用async/await在JavaScript中获取图片尺寸的异步问题

JavaScript读取图片尺寸的异步问题解决

我在JavaScript中读取图片尺寸时遇到了异常行为:设置的三个控制台日志里,读取图片属性的日志总是在内容加载完成后才执行(本该最先执行),导致首次运行时获取到的尺寸始终是0,0。

原代码

var data_indexed = createDataSource(data_array);
console.log("third console - ", data_indexed)
function createDataSource(arr){
          var data = [];
          for (var j=1;j<arr.length;j++){
            var imgWidth1=0;
            var imgHeight1=0;
            // 从索引1开始,跳过id项
            if (arr[j].search("static")==0){
              var getDimensions = async (url) => {
                const img = new Image();
                img.src = url;
                await img.decode();  
                return img;
              };
              getDimensions(arr[j]).then(img => {
                imgHeight1 = img.naturalHeight
                imgWidth1 = img.naturalWidth
                console.log("first console - ",imgHeight1,imgWidth1);
              });
              console.log("second console - ",imgHeight1,imgWidth1);
              data.push(
                {
                  src: `${arr[j]}`,
                  width: imgWidth1,
                  height: imgHeight1,
                  alt: `image ${j}`,
                },)
            }
          } 
          return data;
        }

执行结果

控制台输出结果

修改后的函数(参考woodendoors7和William的回复,供新手参考)

(async()=>{
  var data_indexed = await createDataSource(data_array);
  console.log("third console - ", data_indexed)
})()
async function createDataSource(arr){
  var data = [];
  for (var j=1;j<arr.length;j++){
    // 从索引1开始,跳过id项
    if (arr[j].search("static")==0){
      var imgWidth1 = 0;
      var imgHeight1 = 0;
      var getDimensions = async (url) => {
        const img = new Image();
        img.src = url;
        await img.decode();
        return img;
      };

      let img = await getDimensions(arr[j]);
      imgHeight1 = img.naturalHeight;
      imgWidth1 = img.naturalWidth;
      console.log("first console - ", imgHeight1, imgWidth1);
      console.log("second console - ", imgHeight1, imgWidth1);
      data.push(
        {
          src: `${arr[j]}`,
          width: imgWidth1,
          height: imgHeight1,
          alt: `image ${j}`,
        },)
    }
    
  } 
  return data;
}

内容的提问来源于stack exchange,提问作者Florjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:07:28