【发布时间】:2018-01-18 15:14:22
【问题描述】:
我有一个 Picture 对象数组。我使用.map() 对它们进行迭代,因此我可以将它们中的每一个上传到我的firebase-storage。 Picture 的上传完成后,我想获取Picture 的 URL 并将其放入另一个数组中。
一旦完成所有上传,并且我拥有完整的 URL 数组,我想将 db.push() 数据发送到我的数据库。
问题是db.push() 开始之前我所有的图片都上传完成了!
如何让db.push() 等到.map() 正确完成?
UploadForm(event) {
event.preventDefault();
const db = firebase.database().ref('app').child('cards');
const userId = this.props.user;
//the stuff from the Form
const titel = this.titelInput.value;
const grabtiefe = this.grapTiefeVonInput.value +" - " + this.grapTiefeBisInput.value;
const transportbreite = this.transportbreiteVonInput.value + " - " + this.transportbreiteBisInput.value;
const transporthoehe = this.transporthoeheVonInput.value + " - " + this.transporthoeheBisInput.value;
const gewicht = this.GewichtdesArtikelsInput.value;
const preis = this.priceInput.value;
const desc = this.descInput.value;
const adresse = this.props.address;
const ort = this.props.ort;
const mobil = this.props.mobil;
const festnetz = this.props.festnetz
const array = []
const pictures = this.state.pictures[0]
const keys = Object.keys(pictures)
//the map function start to upload an Array of Pics and gets its URL and Pushes it to an Array.
// after this the map funciton sets the array to this.state.Arr
keys.map((key) => {
const picture = pictures[key]
firebase.storage().ref('images').child('artikelimgaes/'+userId).child('artikel/')
.child(titel).child(picture.name).put(picture)
.then(()=>{
firebase.storage().ref('images').child('artikelimgaes/'+userId).child('artikel/').child(titel).child(picture.name)
.getDownloadURL().then((url) => {
const imgUrl = url;
array.push(url)
this.setState({Arr : array})
})
})
})
// now the Upload of all Data should start
const coordinaten = this.state.cords;
const images = this.state.Arr
const mainImage = this.state.Arr[0]
db.push({
grabtiefe: grabtiefe,
transportbreite: transportbreite,
transporthoehe: transporthoehe,
cardHeading:titel ,
cardPreis: preis,
cardDesc: desc,
gewicht: gewicht,
address: adresse,
ort: ort,
gemietet: 0,
cords: coordinaten,
mobil:mobil ,
festnetz: festnetz,
imageArr: images,
imageUrl: mainImage,
gebiet: this.state.gebiet,
bundesland: this.state.bundesland,
uid: userId,
})
this.setState({
redirect: true
})
}
}
【问题讨论】:
-
returnfirebase 承诺,他们将映射的承诺数组包装成Promise.all
标签: javascript reactjs function firebase ecmascript-6