我正在使用Angular 7,并且我有一个函数,该函数具有promise并将结果保存在如下数组中:
appendImage(item){
this.imageCompress.compressFile(item, 50, 50).then(
result => {
this.compressedImages.push(result);
return this.compressedImages;
});
}
然后我从另一个具有for循环的函数中调用此函数/承诺:
async compressFiles() {
if(this.elementsSelected.length > 0){
for(let i = 0; i < this.elementsSelected.length; i++){
let actual = this.elementsSelected[i].src;
let res = await this.appendImage(actual);
console.log(res);
}
return this.compressedImages;
}else{
console.warn("No Images Selected");
}
}
当所有promise调用结束时,我需要返回数组。当我从appendImage()
函数打印数组时,得到的数组与我想要的一样,但是执行console.log(res)
后得到undefined
。
我在做什么错了?
答案 0 :(得分:0)
为了正确地等待您的功能,您需要返回承诺。
appendImage(item){
this.imageCompress.compressFile(item, 50, 50).then(
result => {
this.compressedImages.push(result);
return this.compressedImages;
});
}
应该是
appendImage(item){
// this is a promise, and you need to return it, in order to use await
return this.imageCompress.compressFile(item, 50, 50).then(
result => {
this.compressedImages.push(result);
return this.compressedImages;
});
}
答案 1 :(得分:0)
您不是要从appendImage返回。
使用异步功能尝试以下操作。
async appendImage(item) {
const result = await this.imageCompress.compressFile(item, 50, 50);
this.compressedImages.push(result);
return this.compressedImages;
}