Javascript 如何同步上传图片?
我试图延迟显示图像,直到所有图像都被上传(在浏览器中),但我的代码仍在继续(不等待上传) 我正在使用承诺和异步等待。这是我的密码:Javascript 如何同步上传图片?,javascript,asynchronous,ecmascript-6,async-await,Javascript,Asynchronous,Ecmascript 6,Async Await,我试图延迟显示图像,直到所有图像都被上传(在浏览器中),但我的代码仍在继续(不等待上传) 我正在使用承诺和异步等待。这是我的密码: async _renderPhotos(data){ console.log("step6.1"); const photoSetDiv = document.createElement("div"); photoSetDiv.classList.add("photoSet"); // photoSetDiv.classList.ad
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));
}
async\u渲染照片(数据){
控制台日志(“步骤6.1”);
const photoSetDiv=document.createElement(“div”);
photoSetDiv.classList.add(“photoSet”);
//photoSetDiv.classList.add(“不可见”);
photoSetDiv.id=`photoSet${this.\u step}`;
consturlarray=data.map(image=>image.url);
等待此消息。_上传图像(数据、photoSetDiv);
控制台日志(“步骤6.3”);
此.u容器.appendChild(photoSetDiv);
}
_上载所有图像(数组、容器){
var指数=0;
//上传每个图片都是单独的承诺
功能检查图像(项目){新承诺((解决、拒绝)=>{
//创造,{
modal.style.display=“块”;
modalImg.src=item.url;
};
})};
返回Promise.all(array.map(checkImage));
}
我想等待上传图像。等价物:
按以下顺序在控制台中显示:
步骤6.1
步骤6.2(由于许多图像而多次执行)
步骤6.3等待和承诺的陷阱之一。所有的/
竞争
都是,你可以在非承诺上使用它们,而非承诺只会对价值本身进行评估。因此:
await undefined;
await Promise.all([ undefined, undefined ]);
将直接运行,不发出任何警告(好的,不完全是这样,它将等待两个微滴答声)
这就是你的情况。您没有
返回从checkImage
创建的承诺,因此您基本上调用promise。所有都在未定义的数组中。您没有从checkImage
返回承诺。