2017-06-15 95 views
0

我對JavaScript很新穎,似乎無法自己找出這個問題: 我想在處理存儲的Cordova項目中使用插件。 基本上,我想這一點:在js中正確使用Promise

if(localStorage.getItem('download_quality')=="4k") 

通過本地存儲的插件來代替。 數據通過存儲:

this.nativeStorage.setItem('download_quality',"4k") 
     .then(
     () => console.log('Stored item!'), 
     error => console.error('Error storing item', error) 
    ); 

根據該文件,我應該使用:

this.nativeStorage.getItem('download_quality').then(
    data => console.log(data), 
    error => console.error(error) 
); 

這工作得很好,但我怎麼能在一個if語句中使用呢?

我已經試過:

var test = this.nativeStorage.getItem('download_quality').then(
      data => {return data}, 
      error => console.error(error) 
     ); 
if(test=="4k") 
... 

,但不起作用。

這樣做的正確方法是什麼?

回答

2

你應該這樣做的方式是承諾的方式,做你的東西在裏面。

this.nativeStorage.getItem('download_quality').then(
    data => { 
    if (data === '4k') { 
     // do something 
    } 
    }, 
    error => console.error(error) 
); 
0

你分配test實際上是對Promise參考。由於您將訪問本地存儲,因此該訪問將以異步方式完成。 A Promise只是未來結果的表示。

您需要將if語句放在函數中,該函數將在promise解析時調用。該功能將收到getItem返回的數據,然後您可以隨心所欲地執行任何操作。

像:

function checkDownloadQuality (downloadQuality) { 
    if (downloadQuality === "4k") { 
    // do something 
    } 
} 
this.nativeStorage.getItem('download_quality').then(
    data => checkDownloadQuality(data), 
    error => console.error(error) 
); 
// or if the nativeStorage API support it: 
this.nativeStorage.getItem('download_quality') 
    .then(checkDownloadQuality) 
    .catch(error => console.error(error)); 
1

使用ES7

async yourMethod() { 
    try { 
     const data = await this.nativeStorage.getItem('download_quality'); 
     if (data === '4k') { 
      // do something 
     } 
    } catch(e) { 
     console.log(e); 
    } 
}