为了账号安全,请及时绑定邮箱和手机立即绑定

关于if语句中的异步请求

关于if语句中的异步请求

Smart猫小萌 2019-02-15 18:19:51
有一个列表需要通过异步接口获取当前位置然后再返回数据,但是我不想每次都请求这个获取位置,我就想先加个判断,有值直接获取列表,没值先获取位置再获取列表,但是问题就来了,因为他是异步的,我没办法写成下面这样:if (!hasLocation) {      getLocationSync()} //TODO :getStoreList然后我现在就改成了这样:if (!hasLocation) {      this.getLocationSync().then(this.getStoreList());} else {      this.getStoreList()}请问有什么优雅的写法吗???
查看完整描述

2 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

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

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

查看完整回答
反对 回复 2019-02-27
?
互换的青春

TA贡献1797条经验 获得超6个赞

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);

})


查看完整回答
反对 回复 2019-02-27
  • 2 回答
  • 0 关注
  • 853 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号