I'm creating gallery page, which will show images fetched from API. I'm doing it via class in ES6. In some moment I need to wait for all images to be loaded (not only from the API but also in my HTML). After that I add/remove particular CSS classes in some containers. Unfortunately my code doesn't want to be asynchronous.

I'm using ES6 class, async/await and promises directly. I've tried lot of solutions, found on the stackoverflow, but nothing is working for me.

//here i want to wait for runFirstSearch and _renderButton to end completely.
async _renderElements(){
    await this.runFirstSearch();
    await this._renderButton();
document.getElementById(`"photoSet${this._step}"`).classList.remove("unvisible");        document.getElementById("showMore").classList.classList.remove("unvisible");
document.getElementById("loader").classList.add("unvisible");
}

// runFirstSearch is using function _renderPhotos:

_renderPhotos(data){
        console.log("step6");
        const photoSetDiv = document.createElement("div");
        photoSetDiv.classList.add("unvisible");
        photoSetDiv.id=`photoSet${this._step}`;
        const urlArray=data.map( image => image.url);


        const checkImage = path => {new Promise (resolve =>{
            const img = new Image();

            img.onload=() => {
                console.log("photo is uploaded");
                photoSetDiv.appendChild(img);
                resolve(path)}
            img.src=path;
        })};
        Promise.all(urlArray.map(checkImage)).then(result => 
        this._container.appendChild(photoSetDiv) );

        // here is my initial, synchronous code when I didn't think about asynchronous -> it can help in understanding my plan.
    //     data.forEach((image, index) =>{
    //         const classCSS = index === 4  ? "photo2":"photo1";
    //         let img= new Image();
    //         img.onload = function(){
    //             console.log("ahfikhfhwoi");
    //             photoSetDiv.appendChild(this);
    //         };
    //         img.src=image.url;
    //         img.classList.add(classCSS);
    //     });

    // this._container.appendChild(photoSetDiv);
    }

I want to wait for resolving of all onload events in function _renderPhotos and after that run to the next element: document.getElementById("photoSet${this._step}").classList.remove("unvisible");

0 Answers