【问题标题】:Using jQuery deferred() and resolve within a function that is within a loop使用 jQuery deferred() 并在循环内的函数中解析
【发布时间】:2013-02-12 14:30:32
【问题描述】:

我有一个全局变量 var imageURL = jQuery.Deferred(); 作为延迟对象。

接下来我有一个通过循环运行的函数,对于每个循环,我打算获取通过异步函数产生的值。我遇到的问题是我无法正确获取值,因为在函数返回它们的值之前调用它们,所以我被告知使用 jQuery deferred。无法完全理解它:

    downloadProductImage: function(remoteImage, localImageName){

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
         fileSystem.root.getFile(localImageName, {create: true, exclusive: false}, function ff1(fileEntry) {
         var localPath = fileEntry.fullPath;
         var ft = new FileTransfer();
         ft.download(remoteImage,
              localPath, function (entry) {
                   imageURL.resolve(entry.fullPath);

                    //return entry.fullPath;

                     }, fail);
                   }, fail);
        }, fail);
}

downloadProductImage函数是循环执行的,在这个函数被调用之后我希望得到imageURL.resolve(entry.fullPath)的值,所以我这样做了:

    //start loop
    imageURL.done(function(theURL){
        alert(theURL);
    });
//end loop

如果我理解正确,文件下载的回调会运行,完成后会执行 imageURL.done()。但是 done() 一直显示相同的文件路径,就好像它正在覆盖每个文件一样。

任何帮助将不胜感激。

【问题讨论】:

  • 您是否尝试多次解析同一个延迟对象?延迟对象只能解析一次。
  • 是的,我正在这样做,没有意识到你只能推迟一个对象。什么是合适的解决方法?
  • 在您的情况下,使用自定义事件或 $.Callbacks 对象会更有意义。

标签: jquery asynchronous jquery-deferred


【解决方案1】:

正如 cmets 中所说,您不能将 imageURL 用作全局变量。 $.Deferred 只能使用一次。当其状态为resolvedrejected时,每次添加.done.fail回调,都会立即返回相同的结果。

您应该做的是删除您的全局 imageURL,并使downloadProductImage 返回一个新的$.Deferred。这样您就可以将.done 添加到返回的$.Deferred

downloadProductImage: function(remoteImage, localImageName) {
    var imageURL = $.Deferred();
    window.requestFileSystem(
        [...]
        ft.download(remoteImage,
            localPath, function (entry) {
                imageURL.resolve(entry.fullPath);
                //return entry.fullPath;
                }, fail);
            }, fail);
    }, fail);
    return imageURL;
}

如果您的文件传输失败,请不要忘记reject您的延期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2013-04-23
    • 2013-03-10
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多