以编程方式创建jQuery的承诺链接的一系列 [英] Programmatically creating a chained sequence of jQuery promises

查看:102
本文介绍了以编程方式创建jQuery的承诺链接的一系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数删除文件列表,文件路径,数组通过调用每个文件的单一DELETEFILE(文件路径)的列表(APIS一些我使用不支持批量删除)。该函数返回的DeleteFile一个jQuery承诺,解决在删除文件/拒绝。

I have a function to delete a list an array of files, filePaths, by calling a single deleteFile(filePath) on each of the files in a list (some APIS I'm using don't support bulk delete). The function deleteFile return a jQuery promise and resolves/rejects upon deleting the file.

function deleteFiles(filePaths)
    var deferreds = $.map(fileKeys, function (val, index) {
        return deleteFile(filePath);
    });

    $.when.apply($, deferreds).then(function (schemas) {
        console.log("DONE", this, schemas);
        deferred.resolve();
    }, function (error) {
        console.log("My ajax failed");
        deferred.reject(error);
    });

我收到.reject呼吁有的在列表中的文件(我知道它们的存在),所以我想我可能需要打开文件路径的数组呼叫的链接,就像一个队列(二/ C这不是$。当呢,不是吗?这似乎发动一次全部)​​。我也知道知道如何做到这一点(如.deleteFile(PATH1).deletePath(PATH2)等,当他们在一个这样的数组。

I am getting .reject calls on some of the files in the list (and I know they exist), so I'm thinking I might need to turn the array of filePaths into a chaining of calls, like a queue (b/c this isn't what $.when does, does it? it seems to launch them all at once). I have know idea how to do this (like .deleteFile(path1).deletePath(path2). etc when they are in an array like this.

任何帮助是提前pciated AP $ P $。

Any help is appreciated in advance.

推荐答案

$。当不发射任何东西,他们在地图中循环启动。 $。当只是简单地返回的承诺数组的承诺。

$.when doesn't launch anything, they were launched in your map loop. $.when simply returns a promise for an array of promises.

如果你想让他们按顺序使用减少:

If you want them sequentially, use reduce:

function deleteFiles(filePaths) {
    return filePaths.reduce(function(cur, next) {
         return cur.then(function() {
             return deleteFile(next);
         });
    }, $().promise());
}

如果你希望他们按顺序,同时也越来越阵列回来了各自的结果:

If you want them sequentially, while also getting the array back with respective results:

function deleteFiles(filePaths) {
    var ret = filePaths.slice(0);
    return filePaths.reduce(function(cur, next, i) {
         return cur.then(function() {
             return ret[i] = deleteFile(next);
         });
    }, $().promise()).then(function(){
         return $.when.apply($, ret);
    })
    //These don't make any sense to call in this function but sure
    .then(function(schemas) {
         console.log("DONE", this, schemas);
    }).fail(function(error) {
         console.log("My ajax failed");
    });
}

这篇关于以编程方式创建jQuery的承诺链接的一系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆