如何使函数兑现承诺

时间:2019-03-05 06:43:03

标签: javascript function promise es6-promise

调用此函数时,我想返回downloadURL,它是一个Firebase上传函数。

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

我尝试了此操作,它没有返回downloadURL

2 个答案:

答案 0 :(得分:2)

您可以按以下方式简单地尝试它:

  1. 将文件导入所需的位置。
  2. 然后使用相关的参数调用该函数。
  3. 在promise中使用 then 方法来获取已解决的downloadUrl

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

答案 1 :(得分:1)

尝试一下。

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

一旦getDownloadURL成功,想法将包括resolve方法。然后可以通过调用上面的答案中提到的方法来获取它

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