一旦“processPhotos”函数的所有承诺都完成,我需要执行函数“finalizeProcess”。
有谁能够帮我?谢谢!!
processPhotos();
finalizeProcess();
processPhotos (){
this.foto1File.generateBlob((blob) => {
ref.child('picture_1').put(blob)
.then((pictureRef) => {
//sentence
})
})
this.foto2File.generateBlob((blob) => {
ref.child('picture_2').put(blob)
.then((pictureRef) => {
//sentence
})
})
}
这样就可以了:
function processPhotos() {
var promise1 = new Promise(resolve => {
this.foto1File.generateBlob(blob => {
ref.child('picture_1').put(blob)
.then(pictureRef => {
resolve(pictureRef);
});
});
});
var promise2 = new Promise(resolve => {
this.foto2File.generateBlob(blob => {
ref.child('picture_2').put(blob)
.then(pictureRef => {
resolve(pictureRef);
});
});
});
Promise.all([promise1, promise2]).then(results => {
// do something with results here
finalizeProcess();
});
};
至于trincot所说的,你可以使用Promise.all
将函数存储到变量中,然后一起解析promise。
processPhoto(){
const firstPromise = this.fotoFile.generateBlob(blob => {
//[..]
}
const secondPromise = this.foto2File.generateBlob(blob => {
//[...]
}
const [foto1File, foto2File] = Promise.all([firstPromise, secondPromise]);
}
当然,在每个函数中,请确保返回promise本身。
这里有另一种选择,类似于answer of davmich。但不是在finalizeProcess
中调用processPhotos
而是返回一个承诺,你可以用来调用finalizeProcess
。
function processPhotos() {
return Promise.all([
new Promise(resolve => {
this.foto1File.generateBlob(blob => {
ref.child('picture_1').put(blob).then(resolve);
});
}),
new Promise(resolve => {
this.foto2File.generateBlob(blob => {
ref.child('picture_2').put(blob).then(resolve);
});
})
]);
}
processPhotos().then(pictureRefs => finalizeProcess());
或者,您可以先展开处理。
ref.child('picture_1').put(blob).then(resolve);
变为:
ref.child('picture_1').put(blob).then(pictureRef => {
// do stuff with pictureRef
resolve(/* custom value */);
});