鍍金池/ 問答/HTML/ 關(guān)于if語句中的異步請求

關(guān)于if語句中的異步請求

有一個列表需要通過異步接口獲取當(dāng)前位置然后再返回數(shù)據(jù),但是我不想每次都請求這個獲取位置,我就想先加個判斷,有值直接獲取列表,沒值先獲取位置再獲取列表,但是問題就來了,因為他是異步的,我沒辦法寫成下面這樣:

if (!hasLocation) {
      getLocationSync()
}
 
//TODO :getStoreList

然后我現(xiàn)在就改成了這樣:

if (!hasLocation) {
      this.getLocationSync().then(this.getStoreList());
} else {
      this.getStoreList()
}

請問有什么優(yōu)雅的寫法嗎???

回答
編輯回答
淚染裳

三目表達(dá)式:hasLocation ? this.getStoreList() : this.getLocationSync().then(this.getStoreList());

2017年11月20日 17:33
編輯回答
別逞強(qiáng)
let cacheList = Cache['list'];
new Promise((resolve, reject) => {
    if (cacheList && cacheList.length) {
        resolve(cacheList);
        return;
    }
    this.getLocationSync()
    .then(list => {
        // 緩存
        Cache['list'] = list;
        resolve(list);
    })
    .catch(reject);
})
.then(list => {
    console.log(list);
})
2018年2月1日 06:58