我正在使用firebase并注意到大多数方法都在返回promise,但在文档中这个不是。是否有可能将此变为承诺?
uploadTask.on(
'state_changed',
function(snapshot) {
const progress = snapshot.bytesTransferred / snapshot.totalBytes * 100;
console.log('Upload is ' + progress + '% done');
},
function(error) {
alert(error);
},
function() {
const downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
}
);
答案 0 :(得分:2)
如果您希望在上传完成时解决某些承诺,请使用此通用模式:
const promise = new Promise((resolve, reject) => {
// whenever the work is complete and successful
resolve()
// or, whenever the work finishes with an error
reject()
})
According to the API docs,对于适用于Firebase UploadTask的云端存储,您的on
处理程序将收到"完成"的回调作为您的第四个参数。所以你可以像这样修改它:
const promise = new Promise((resolve, reject) => {
uploadTask.on(
'state_changed',
function(snapshot) {
const progress = snapshot.bytesTransferred / snapshot.totalBytes * 100;
console.log('Upload is ' + progress + '% done');
},
function(error) {
reject(error); // added this line
alert(error);
},
function() {
const downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
resolve(); // added this line
}
);
});
您可以看到我在您的代码中添加了对resolve
和reject
的调用,现在已嵌入到Promise中的闭包中。