Reputation: 6027
I am using firebase and notice that most of the method's are returning promises, but in the documentation this one is not. Is it possible to change this into a 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);
}
);
Upvotes: 2
Views: 1179
Reputation: 317760
If you want some promise to resolve when the upload is complete, use this generalized pattern:
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, for a Cloud Storage for Firebase UploadTask, your on
handler will receive an a callback for "complete", as your fourth argument. So you can modify it like this:
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
}
);
});
You can see that I added calls to resolve
and reject
in your code, now embedded in a closure inside a Promise.
Upvotes: 6