首页 > 解决方案 > 如何同步上传图片?

问题描述

我尝试延迟显示图像,直到所有图像都被上传(在浏览器中),但我的代码继续运行(不等待上传)。

我正在使用承诺和异步等待。这是我的代码:

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

    await this._uploadAllImages(data, photoSetDiv);
    console.log("step6.3");
    this._container.appendChild(photoSetDiv);

}

 _uploadAllImages(array, container){
    var index=0;

    //upload each of the images is  separate promise
    function checkImage(item){new Promise ((resolve, reject) =>{

        //Creating <figure>, <img> and <div>.
        const figure = document.createElement("figure");
        figure.classList.add(item.site);
        const title = document.createElement("div");
        title.classList.add("titleImage");
        title.innerHTML =`#${item.site}`;
        figure.appendChild(title);
        const img = new Image();
        img.classList.add("image");

        img.onload=() => {
            console.log("step 6.2");
            const classCSS=figureClass(index);
            figure.classList.add(classCSS);
            figure.appendChild(img);
            container.appendChild(figure);
            index ++;
            resolve(item)}

        img.src=item.url;
        // Event on the image: after clicking on the image it is erlarged
        img.onclick= () => {
            modal.style.display = "block";
            modalImg.src=item.url;
        };
    })};

    return  Promise.all(array.map(checkImage));
}

我想等待上传图片。等效:在控制台中按如下顺序显示:step 6.1 step 6.2(多次因为图片多) step 6.3

标签: javascriptasynchronousecmascript-6async-await

解决方案


awaitand Promise.all/的陷阱之一race是,您可以将它们用于非承诺,这只会评估价值本身。所以这:

  await undefined;
  await Promise.all([ undefined, undefined ]);

将直接运行,不会发出任何警告(好吧,不完全是,它会等待两个微滴答声)。

这就是你的情况。您没有return从 中创建承诺checkImage,因此您基本上调用Promise.all了一个 s 数组undefined


推荐阅读