关于if语句中的异步请求

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

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

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

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

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

阅读 4k
3 个回答

三目表达式: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);
})
async demo(hasLocation) {
      if (!hasLocation) {
        await this.getLocationSync()
      }
      this.getStoreList()
}

getLocationSync() {
    let _this = this
    return new Promise((reslove, reject) => {
      getCount({phone: _this.params.phone}).then((res) => {
          reslove(res.data.count)
      })
    })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题