承诺被拒绝后AngularJS清理

时间:2016-08-16 14:31:54

标签: angularjs

我需要通过调用一组$ http请求(通过ngResource)来创建基本层次结构,并且当任何调用未能给用户另一次尝试时需要进行清理。比方说,层次结构是城市 - >街 - >人,城市可以有更多的街道和街道更多的人。

我使用的主要代码如下:

/* city is object with cityid: {id: cityId} */
function createCity(city) {
    return City.save(null, city).$promise;
}

/* streets is array with objects {id: streetId, city: cityId} */
function createStreets() {
    var promises = [];
    for (var i = 0; i< streets.length; i++) {
        promises.push(Street.save(null, streets[i]).$promise);
    }
    return $q.all(promises);
}

/* person is array with objects {id: personId, street: streetId} */
function createPerson() {
    var promises = [];
    for (var i = 0; i< person.length; i++) {
        promises.push(Person.save(null, person[i]).$promise);
    }
    return $q.all(promises);
}

/* city is object {id: cityId} */
function removeCity() {
    return City.delete(city).$promise; 
}

/* streets array with objects as for createStreets method */
function removeStreets() {
    var promises = [];
    for (var i = 0; i< streets.length; i++) {
        promises.push(Street.delete({id: streets[i].streetId}).$promise);
    }
    return $q.all(promises);
}

/* person array with objects as for createPerson method */
function removePerson() {
    var promises = [];
    for (var i = 0; i< person.length; i++) {
        promises.push(Person.delete({id: person[i].personId}).$promise);
    }
    return $q.all(promises);
}

/* should clean the hierarchy in reversed order */
function cleanup() {
    return removePerson()
        .then(removeStreets)
        .then(removeCity);
}

/* main method */
function buildHierarchy() {
    return createCity()
       .then(createStreets)
       .then(createPerson)
       .catch(cleanup);
}

// somewhere in the code
buildHierarchy();

我希望当抛出错误时,清理方法中的方法将按顺序执行。但是在开发人员控制台中我可以看到,即使方法似乎按正确的顺序调用,执行也是错误的 - 尝试在删除所有Person和Streets之前移除City,这是不允许的。

有没有人知道,如何确保以正确的顺序删除对象。似乎在捕获阻止之后,承诺链不起作用。

感谢您的任何帮助/想法。

米甲

2 个答案:

答案 0 :(得分:0)

问题可能出在你的删除功能中。 removePersonremoveStreets返回promises数组。在其他函数中,返回$q.all(promises),它返回一个promise。

答案 1 :(得分:0)

感谢所有笔记,我能够在原始代码中找到问题。我觉得值得在这里提一下这个问题,因为它更多次发生在我身上。

重要说明:感谢@Todd Miller的评论我修复了问题中的示例,即使这不是我遇到的问题的核心。

这是示例中的重要部分,有效:

/* should clean the hierarchy in reversed order */
function cleanup() {
    return removePerson()
        .then(removeStreets)
        .then(removeCity);
}

这是我原始资源中的代码,但不起作用:

/* should clean the hierarchy in reversed order */
function cleanup() {
    return removePerson()
       .then(removeStreets())
       .then(removeCity());
}

注意.then()块中的括号。自动填充功能非常有用,但有时可能会误导您。

相关问题