簡體   English   中英

如何在bluebird.js內部調用函數

[英]How to call a function inside bluebirdjs promise

我正在嘗試使用bluebirdjs獲得一個promise函數。 但是所有嘗試都失敗了,因為也許我不知道自己在做什么...?

我想獲取文件位置,然后一個接一個地下載文件,然后推送到數組。

import * as Promise from 'bluebird';
fileFunction(files){
  Promise.map(files, function(file) {
    // Promise.map awaits for returned promises as well.
    //Promise.delay(1000);
     return this.getLocation(file); 
    },
  ).then((file) => {
      console.log('done')
    });

}

getLocation(file){
 if(file){
  return this._storage.ref(file).getDownloadURL().subscribe(url => 
      this.img_array.push(url)
  );
 }

當我調用返回this.getLocation(file)...時,我收到以下error bluebird.js:1545 Unhandled rejection TypeError: Cannot read property 'getLocation' of undefined ....bluebird.js

編輯部分代碼正在使用中!

 fileFunction(files){
    return Promise.map(files, file => {
       return this.getDownloadUrl(file); 
    }).then(locations => {
        // add these locations onto this.img_array
        this.img_array.push(...locations);
        console.log('done');
        return locations;
    });
  }


getFiles(e): Promise<any>{
  this.outPutFiles = e;

 this.fileFunction(this.outPutFiles).then(locations => {
  locations.map((arr) => arr.subscribe((files) => this.downloadUrls.push(files)));
  }).catch(err => {
      console.log(err);
  });
}


getDownloadUrl(file){
  if(file){
    return this._storage.ref(file).getDownloadURL();
   } else {
    return Promise.reject(new Error('No file passed to getLocation'));
   }
}

this.getLocation(file)不起作用,因為您丟失了this的值,因為您位於Promise.map()回調內部。 請記住,在Javascript中每一個正常的函數調用值改變this ,除非你專門控制值this

您可以使用簡單的箭頭函數為您的回調解決問題的這一部分,如下所示:

fileFunction(files){
  return Promise.map(files, file => {
     return this.getLocation(file); 
  }).then(locations => {
      // add these locations onto this.img_array
      this.img_array.push(...locations);
      console.log('done');
      return locations;
  });
}

假定this.getLocation(file)返回一個可以解析為位置值的promise。 您確定這樣做嗎? 看來您遇到的問題可能不僅僅是您遇到的第一個錯誤。


並且,在進行旁聊之后,您還需要修復getLocation()以返回解析為所需URL的Promise。 getDownloadURL() Javascript文檔中getDownloadURL() ,似乎getDownloadURL()已經返回了一個可解析為所需URL的getDownloadURL() 因此,您可以只返回該承諾,並讓Promise.map()為您管理結果。

getLocation(file){
 if(file){
  return this._storage.ref(file).getDownloadURL();
 } else {
  return Promise.reject(new Error("No file passed to getLocation"));
 }
}

然后,您將像這樣使用它:

obj.fileFunction(fileArray).then(locations => {
    console.log(locations);
}).catch(err => {
    console.log(err);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM