使用promises从动态数量的ajax调用中获取数据

时间:2014-05-11 19:25:12

标签: javascript jquery ajax

我有一些动态数量的ajax调用,我需要在其中使用看起来像的承诺:

  saveNewProjects(projects) {
    var projectPromises: any[] = [];

    for (var projectName in projects) {
        var project = projects[projectName][0].Project;
        if (project && project.id == 0 && project.name !== null) {
            var deferred = $.Deferred();
            (function(deferred) {
                        $.ajax({
                        url: "projects",
                        contentType: "application/json",
                        type: "POST",
                        data: JSON.stringify(project),
                        crossDomain: $.support.cors,
                        xhrFields: {
                            withCredentials: $.support.cors,
                        },
                        success: function (data) {
                            deferred.resolve(data);
                        },
                    });
                    projectPromises.push(deferred);
                })(deferred);
        }
    }
    return $.when.apply($, projectPromises).promise();
}

  this.saveNewProjects(bioSamplesByProject).then(() => {
            console.log("i'm done");
            console.log(arguments);

但是参数是一个空数组。如何获取每个promise的数据,以便我可以为每个promise提供成功和失败的回调,并在完成所有ajax调用时执行某些操作?

0 个答案:

没有答案