当用异步线程处理业务时,比如:在实时搜索用户的信息时,至少找到一个用户,正常显示匹配的用户;如果一个都找不到,则显示“暂无数据”;好,问题来了,假如这里有 A、B 两个异步请求,假设 A 是一个都找不到的情况,B 是至少找到一个用户,而且 A 先开始请求,B 再请求,但 B 先返回,显示找到的用户,但此时 A 又回来了,显示 "暂无数据",按理说此时的正确答案应该是:找到用户的情况,因为 B 是最后请求的,结果也根据最新一次的请求来。所以出BUG了。
searchChild(e) {
this.showClearBtn = true
this.childList = []
this.isLoad = true
this.noChild = false
this.defaultText = false
clearTimeout(inputTimer)
//延迟触发事件
inputTimer = setTimeout(() => {
let searchName = e.detail.value
if (searchName && searchName.length > 0) {
user.getChild({
userName: searchName
}).then(r => {
this.isLoad = false
if (r.success) {
this.childList = r.data
// this.noChild = false // [2]
} else {
// this.noChild = true // [2]
}
this.noChild = this.childList.length > 0 ? false : true // [1]
}).catch(e => {
uni.showToast({
icon: 'none',
title: '服务异常,请稍后再试'
})
})
} else {
this.isLoad = false
this.defaultText = true
}
}, 400)
}
解决方案:看 [1] 代码处,也很简单,只要在判断完之后最后再进行判断一下即可。千万不能像 [2] 处把它给写死。