2017-08-13 59 views
3

我想要一個承諾解析後返回一個布爾值,但打字稿給出了一個錯誤說承諾後打字稿返回布爾解決

A 'get' accessor must return a value.

我的代碼如下所示。

get tokenValid(): boolean { 
    // Check if current time is past access token's expiration 
    this.storage.get('expires_at').then((expiresAt) => { 
     return Date.now() < expiresAt; 
    }).catch((err) => { return false }); 
} 

此代碼適用於Ionic 3 Application,存儲是Ionic Storage實例。

+2

你不能做到這一點...您可以通過只返回返回'無極'' this.storage.get ...'雖然。 – Gerrit0

+0

@ user2473015我通常沒有在get中看到異步代碼,而是異步進程設置了一個屬性,get得到了... – JGFMK

+1

而且你可能不應該爲有副作用的東西使用getter。 – Bergi

回答

3

可以返回一個Promise解析爲這樣的布爾:

get tokenValid(): Promise<boolean> { 
    // | 
    // |----- Note this additional return statement. 
    // v 
    return this.storage.get('expires_at') 
    .then((expiresAt) => { 
     return Date.now() < expiresAt; 
    }) 
    .catch((err) => { 
     return false; 
    }); 
} 

的代碼在你的問題只有兩個return語句:一個無極的then處理程序內和一個其catch處理程序中。我們在tokenValid()訪問器中添加了第三個return語句,因爲訪問者也需要返回一些內容。

這裏是一個工作示例in the TypeScript playground

class StorageManager { 

    // stub out storage for the demo 
    private storage = { 
    get: (prop: string): Promise<any> => { 
     return Promise.resolve(Date.now() + 86400000); 
    } 
    }; 

    get tokenValid(): Promise<boolean> { 
    return this.storage.get('expires_at') 
     .then((expiresAt) => { 
     return Date.now() < expiresAt; 
     }) 
     .catch((err) => { 
     return false; 
     }); 
    } 
} 

const manager = new StorageManager(); 
manager.tokenValid.then((result) => { 
    window.alert(result); // true 
}); 
+0

向問題添加了其他信息。 – user2473015

+0

@ user2473015恐怕我不知道在這個答案中提供了哪些附加信息。 –

1

你的功能應該是:

get tokenValid(): Promise<Boolean> { 
    return new Promise((resolve, reject) => { 
     this.storage.get('expires_at') 
     .then((expiresAt) => { 
      resolve(Date.now() < expiresAt); 
     }) 
     .catch((err) => { 
      reject(false); 
     }); 
}); 
}