简体   繁体   中英

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

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) );

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM