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

互换的青春
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);
})
添加回答
举报
0/150
提交
取消