XHR在for循环中同时运行

时间:2013-06-18 02:10:23

标签: javascript appcelerator appcelerator-mobile

所以我有一个for循环,它遍历一个变量数组,并为每个变量打开一个新的XHR连接(将图像上传到服务器)。

问题是,它会遍历所有项目并在第一次上传完成之前运行下一个上传。如果一个人一次上传大量文件,这并不理想。

有什么办法可以强制循环停止直到XHR连接完成?

谢谢!

2 个答案:

答案 0 :(得分:0)

请参阅http://www.html5rocks.com/en/tutorials/async/deferred/

以及此处的更多讨论https://github.com/caolan/async

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

答案 1 :(得分:0)

在伪代码中,抛出一点点jQuery:

Get list of files from upload dialog box
For each File {
    create FormData object, append File to it.
    create xhr object, set parameters (url, etc.)

    // This is the callback run whenever an upload job comletes
    xhr.onload = {  
        if there's another xhr upload queued {
            dequeue it
        }
        if there's another entry in the completed queue {
            dequeue it
        } else {
            all uploads complete: tidy up
        }
    }
    // An extra to let the user know what's happening
    xhr.onprogress {
        update whatever progress bar we have
    }
    // add jobs to two queues. The first queue contains the actual
    // upload jobs that are dequeued by the onload callback
    // Because uploads may not finish in the order they were started
    // we track the completed jobs in a second queue. The onload callback
    // also dequeues this, and if the queue is empty knows to tidy up.
    add xhr job to queue
    add no-op job to completed queue 
}
// at this point everything is queued. Start the process...
for (number of concurrent uploads) {
    dequeue an xhr job
}
// Sit back and wait... As the initial batch of xhr jobs complete
// their respective onload callbacks each start another upload job
// until they're all done. The last callback to execute turns out the lights...

因为这是异步代码,所以并不总是按照预期的顺序发生。 onload回调在作业排队之前设置,但在作业完成后执行。可能需要一段时间才能解决这个问题。

这个伪代码取自我为图像管理器项目编写的文件上传器的jQuery实现。它利用jQuery .queue方法来存储和跟踪剩余的xhr作业。实际代码太复杂,无法在此重现。