Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从XMLHttpRequest中延迟_Javascript_Xmlhttprequest_Deferred - Fatal编程技术网

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处理程序正在被调用,并且确实解决了你的延迟问题吗?这仍然让我很生气。