Javascript 从XMLHttpRequest中延迟
我正在使用 奇怪的是,当我把它们像那样相互嵌套在一起时:Javascript 从XMLHttpRequest中延迟,javascript,xmlhttprequest,deferred,Javascript,Xmlhttprequest,Deferred,我正在使用 奇怪的是,当我把它们像那样相互嵌套在一起时: foo2 = -> d = new Deferred() setTimeout -> d.resolve("I am foo2") ,400 d.promise() foo1 = -> d = new Deferred() setTimeout -> foo2().then (res)-> console.log(res)
foo2 = ->
d = new Deferred()
setTimeout ->
d.resolve("I am foo2")
,400
d.promise()
foo1 = ->
d = new Deferred()
setTimeout ->
foo2().then (res)->
console.log(res)
d.resolve("I am foo1")
,500
d.promise()
foo1.done (res)-> console.log(res)
它起作用了
但如果我尝试在xhr
中解析deferred,则会依次调用xhr
,它不起作用:
foo2 = ->
d = new Deferred()
xhr = new XMLHttpRequest()
xhr.open('GET', "http://blabla.com/some_other.json", true)
xhr.onreadystatechange = ->
d.resolve("I am foo2") if xhr.readyState is 4 and xhr.status is 200
xhr.send()
d.promise()
foo1 = ->
d = new Deferred()
xhr = new XMLHttpRequest()
xhr.open('GET', "http://blabla.com/some.json", true)
xhr.onreadystatechange = f->
if xhr.readyState is 4 and xhr.status is 200
foo2().then (res)-> # It calls foo2 but never resolves its deferred
console.log(res)
d.resolve("I am foo1")
xhr.send()
d.promise()
foo1.then (res)-> console.log(res)
奇怪的是,如果我在第二个示例中更改
foo2
,并使用回调,一切正常。我在那里看到了coffeescript的一瞥?嗯,可能是调用http://blabla.com/
没有成功吗?您也不会在错误情况下拒绝延迟。不…不,我使用的URL是合法的。。。这个blabla.com只是一个例子。你能确认readystate处理程序正在被调用,并且确实解决了你的延迟问题吗?这仍然让我很生气。