drawing image on HTML Canvas gives error: “Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable”

I am trying to do pixel sorting and drawing an image afterwards. The problem is that sometimes the image loads after sorting and sometimes it gives the above mentioned error. From console, the error is apparently coming from ‘let newImageData’ which you will find in second function. The variables newColorArr and img are global. Here’s my code:

function processImg(image, callback) {
    image.onload = ()=> {
        c.drawImage(image, 0, 0, image.width, image.height);
        let imageData = c.getImageData( 0, 0, image.width, image.height);
        callback(imageData); 
    } 
}



function applyFilter(imageData) {
    colorArr2D = make2DArr(imageData);
    sorted2DArr = selectionSort(colorArr2D);
    fillNewArr(sorted2DArr);
    let newImageData = new ImageData(newColorArr, img.width, img.height);
    c2.putImageData(newImageData, 0,0);
}

How do I solve this issue?