关于if语句中的异步请求

有一个列表需要通过异步接口获取当前位置然后再返回数据,但是我不想每次都请求这个获取位置,我就想先加个判断,有值直接获取列表,没值先获取位置再获取列表,但是问题就来了,因为他是异步的,我没办法写成下面这样:


if (!hasLocation) {

      getLocationSync()

}

 

//TODO :getStoreList

然后我现在就改成了这样:


if (!hasLocation) {

      this.getLocationSync().then(this.getStoreList());

} else {

      this.getStoreList()

}

请问有什么优雅的写法吗???


Smart猫小萌
浏览 854回答 2
2回答

拉风的咖菲猫

三目表达式:hasLocation ? this.getStoreList() : this.getLocationSync().then(this.getStoreList());

互换的青春

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);})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript