-
Notifications
You must be signed in to change notification settings - Fork 139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ajax请求序列化问题 #29
Labels
Comments
buttonA.onclick = function(){
get('/a', function(resTxt){
console.log(resTxt)
input.value = resTxt
})
}
buttonB.onclick = function(){
get('/b', function(resTxt){
console.log(resTxt)
input.value = resTxt
})
}
function get(url, callback){
if(!Array.isArray(get.xhrQueue)){
get.xhrQueue = []
}
var xhrQueue = get.xhrQueue
var xhr = new XMLHttpRequest()
xhrQueue.push(xhr)
xhr.opts = {}
xhr.onloadend = function(){
this.opts.finished = true
checkQueue()
}
xhr.opts.finished = false
xhr.opts.callback = callback
xhr.timeout = 1000*8
xhr.open('get', url, true)
xhr.send()
function checkQueue(){
var xhr = xhrQueue[0]
while(xhr && xhr.opts.finished){
if(xhr.status == 200 || xhr.status == 304){
xhr.opts.callback(xhr.responseText)
}
xhrQueue.shift()
xhr = xhrQueue[0]
}
}
} |
这个问题是不是也可以用Promise 解决 |
不是应该把第二个的填充放到第一个填充函数的callback?(所以也可以promise? |
核心是队列的思想 |
es6伪代码, 忽略细节和错误处理
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
某个应用模块由文本框 input,以及按钮 A,按钮 B 组成。点击按钮 A,会向地址 urlA 发出一个 ajax 请求,并将返回的字符串填充到 input 中(覆盖 input 中原有的数据),点击按钮 B,会向地址 urlB 发出一个 ajax 请求,并将返回的字符串填充到 input 中(覆盖 input 中原有的数据)。
当用户依次点击按钮 A、B 的时候,预期的效果是 input 依次被 urlA、urlB 返回的数据填充,但是由于到 urlA 的请求返回比较慢,导致 urlB 返回的数据被 urlA 返回的数据覆盖了,与用户预期的顺序不一致。
请问如何设计代码,解决这个问题? ——题目来自知乎
The text was updated successfully, but these errors were encountered: