javascript - 如何同步上传图片?
问题描述
我尝试延迟显示图像,直到所有图像都被上传(在浏览器中),但我的代码继续运行(不等待上传)。
我正在使用承诺和异步等待。这是我的代码:
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
解决方案
await
and Promise.all
/的陷阱之一race
是,您可以将它们用于非承诺,这只会评估价值本身。所以这:
await undefined;
await Promise.all([ undefined, undefined ]);
将直接运行,不会发出任何警告(好吧,不完全是,它会等待两个微滴答声)。
这就是你的情况。您没有return
从 中创建承诺checkImage
,因此您基本上调用Promise.all
了一个 s 数组undefined
。
推荐阅读
- python-3.x - 通过 Xarray 保存 NetCDF,尺寸由两个坐标给出
- kubernetes - kubectl exec 错误拨号后端:x509:证书由未知机构签名
- r - 用列的平均值计算数据虹膜
- python - 区间 [0,360] 中两个向量之间的角度
- python-3.x - 无法使用 PyPDF2 在 jupyter notebook 上打开我的 pdf 文件
- r - 计算R中Tobit的虚拟边际效应(及其标准误差)
- magento2 - 自动重新索引后无法应用 Magento 2 目录规则
- c# - 如何简单地添加两位小数并四舍五入到最接近的两位小数?
- python - 在 PCA 中获取两个以上特征值时出错
- php - 如何在 php 中使用 json decode 从数据库中获取数据并显示如下结果?