写了一个判断图片地址是否存在的方法,用到了promise,map遍历后成了一个[Promise]对象,导致拿不到值
const newImgList = imageList.map(async item => {
const res = await this.checkImgExists(this.baseUrl + item)
return {
img: res
}
})
console.log(newImgList);
const checkImgExists = (imgurl) => {
return new Promise(function (resolve, reject) {
var ImgObj = new Image()
ImgObj.src = imgurl
ImgObj.onload = function () {
resolve(imgurl)
}
ImgObj.onerror = function (err) {
reject('/static/img/failImg.png')
}
})
},
打印newImgList结果如下:
转为普通数组方法: Promise.all
Promise.all(newImgList).then((res) => {
console.log(res);
})