【发布时间】:2021-06-14 13:33:54
【问题描述】:
var value = await this.upload();
if (value == true) {
this.item.photos = this.uploaded;
this.item.price = null;
this.item.qty = null;
this.dataSrv.addItem(this.item)
.then(() => {
this.dataSrv.stopLoading();
this.dataSrv.toast('Item Added Successfully');
this.item = {} as Item;
this.pictures = ['', '', '', ''];
this.uploaded = [];
this.photos = ['', '', '', ''];
})
.catch(err => {
this.dataSrv.stopLoading();
this.dataSrv.toast('Error While Adding Item. Try Again Later');
console.log(err);
});
}
在上面的代码中,我正在调用上传函数将图片上传到谷歌存储,我正在等待,所以我可以将图片链接添加到上传的数组中,这会将其保存到 this.item.photos 但它不会等待,而是直接执行真实条件。
async upload(image?) {
var counter = 0;
this.pictures.forEach(i => {
if (i != '') {
let temp: string = (i) as string;
temp = temp.replace("data:image/jpg;base64, ", '');
temp = temp.replace("data:image/jpg;base64,", '');
temp = temp.replace('must use [property]=binding:', '');
temp = temp.replace('SafeValue', '');
temp = temp.replace('(see https://g.co/ng/security#xss)', '');
const randomId = Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36);
const uploadTask = this.storage.ref('items/').child(randomId).putString(temp, 'base64', {
contentType: 'image/png'
});
uploadTask
.then(response => {
console.log("uploaded");
console.log(response);
this.storage.ref('items/' + randomId).getDownloadURL().subscribe(url => {
this.uploaded.push(url);
counter++;
});
})
.catch(err => {
console.log('not uploaded');
});
}
});
if (counter != this.uploaded.length) {
return false;
} else {
return true;
}
}
我尝试在上传函数中返回 Promise 类型,但没有任何改变 我也尝试在函数调用之后执行 then 但同样的问题发生了
注意图片数组包含base64图片
【问题讨论】:
-
我认为你应该在
upload函数中返回一个承诺。否则你不会等待uploadTask终止。 -
我已经尝试将它作为异步上传(图片?):Promise
但它仍然没有等待 -
它似乎返回了一个uploadTask,这不是一个承诺,你必须将它包装在一个承诺中。 :See here
标签: angularjs typescript ionic-framework angular-promise