Kuro Ombu
Kuro Ombu

Reputation: 59

How to make a function return a promise

I want to return downloadURL when this function is called, it's a firebase upload function.

import { storage } from "./base";
import firebase from "firebase";

function uploadFile(file, metadata) {
  return new Promise((resolve, reject) => {
    const task = storage.child(`/${file.name}`).put(file, metadata);

    task.on(
      firebase.storage.TaskEvent.STATE_CHANGED,
      function(snapshot) {
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log(progress);
      },
      function(error) {
        switch (error.code) {
          case "storage/unauthorized":
            break;
          case "storage/canceled":
            break;
          case "storage/unknown":
            break;
          default:
            break;
        }
        reject(error);
      },
      function() {
        task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
            resolve(downloadURL);
          console.log(downloadURL);
        });
      },
    );
  });
}

export { uploadFile };

I tried this, it doesn't return the downloadURL

Upvotes: 2

Views: 431

Answers (2)

Nithya Rajan
Nithya Rajan

Reputation: 4884

you can simply try it as follows:

  1. import the file where you need.
  2. Then call the function with the relevant params.
  3. Use then method in promises to get the resolved downloadUrl

    uploddFile(file, data).then(downloadUrl => console.log(downloadUrl) );

Upvotes: 1

freakomonk
freakomonk

Reputation: 614

Try this.

         import { storage } from "./base";
         import firebase from "firebase";

         function uploadFile(file, metadata) {
          return new Promise((resolve, reject) => {
          const task = storage.child(`/${file.name}`).put(file, metadata);

          task.on(
           firebase.storage.TaskEvent.STATE_CHANGED,
            function(snapshot) {
             var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log(progress);
      },
      function(error) {
        switch (error.code) {
          case "storage/unauthorized":
            break;
          case "storage/canceled":
            break;
          case "storage/unknown":
            break;
          default:
            break;
        }
        reject(error);
      },
        task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
            resolve(downloadURL);
          console.log(downloadURL);
        });
      ,
    );
  });
}

Idea is to include resolve method once the getDownloadURL is succeeded. Then this can be retrieved by calling as mentioned in the above answer

     uploadFile(file, metaData)
     .then((download) => console.log(downloadURL)) ; // Or whatever you want to do wth downloadURL

Upvotes: 1

Related Questions