等待img.同步函数内部的Onload



我有一个需要等待img的情况。Onload函数调整图片的大小。img。Onload函数位于同步函数中,它不能是异步的。我需要等飞机。在我可以继续同步函数之前,先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);
}

这是我目前所知道的。我知道。Onload稍后执行,console.log(x)在此之前触发,但它需要在此之后执行。很遗憾,我不能把它移到img中。Onload,因为这个函数test用于上传,否则不起作用。

谢谢你的建议。

编辑:

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

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()

如果这是一个有用的解决方案,请投票回答,提前感谢。

最新更新