0

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

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

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

谢谢!

4

2 回答 2

0

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

在这里进行更多讨论https://github.com/caolan/async

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);
于 2013-06-18T03:57:23.573 回答
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 作业。实际代码太复杂,无法在此处重现。

于 2013-06-18T16:32:11.137 回答