在同步函数中等待 img.onload

Wait for img.onload inside a synchronious function

我有一种情况需要等待 img.onload 函数来调整图片大小。 img.onload 函数位于不能异步的同步函数中。 我需要等待 img.onload 才能在同步函数中继续。

有没有人知道如何实现它?

示例:

  function test(img) {
    const img =  new Image();

    img.onload = function () {
       //Here needs something to happen, set a variable
       x = value;
    };

    //After the img.onload I need to access this here
    console.log(x);
  }

这是我目前所拥有的。 我知道 img.onload 将在稍后执行并且 console.log(x) 在此之前被触发,但它需要在之后执行。遗憾的是,我不能将其移至 img.onload,因为此功能测试用于上传,否则将无法工作。

感谢任何提示。

编辑:

上传前我用来调整图片大小的实际代码。 上传发生在测试函数中,在此代码之后:

img.onload = function () {
    URL.revokeObjectURL(this.src);
    const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
    const canvas = document.createElement("canvas");
    canvas.width = newWidth;
    canvas.height = newHeight;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, newWidth, newHeight);
    canvas.style = "display: none";
    canvas.toBlob(
        (blob) => {
            // Handle the compressed image. es. upload or save in local state
            let file_small = new File([blob], name,{type:"image/jpeg", lastModified:new Date().getTime()});
            let container = new DataTransfer();
            container.items.add(file_small);
            ajaxData.set('upload', container.files[0]);
            console.log("END of the onload");
                },
            MIME_TYPE,
            QUALITY
        );
};

以下是示例,但您可以根据需要进行更新。

async function test() {
  const myImage = new Image(100, 200);
  myImage.src = 'https://images.kiwi.com/airlines/128x128/0B.png';
  document.body.appendChild(myImage);
  await callFunction(myImage);
  console.log('called second');
}

function callFunction(img) {
  return new Promise((resolve, reject) => {
    img.onload = () => {
        //here you all code goes
        console.log('called first');
        resolve(true)
    }
  })
}

test()

如果这是一个解决方案,请投票作为有用的答案,在此先感谢您。