这种情况是否适合$ q?

时间:2015-06-26 20:32:51

标签: javascript angularjs

我无法确定是否应该将$q用于以下伪造的编码方案:

function create() {

    if (condition1) {
        // ajax call that needs to update
        // the object to be passed into Service.create()
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    Service.create(object).success(function() {
        // the object was passed here
    });

}

注意:condition1condition2是互斥的。

以前,我做过类似的事情:

function create() {

    if (condition1) {
        // on ajax success
        callServiceCreate(object);
        return;
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    callServiceCreate(object);

}

function callServiceCreate(object) {

    Service.create(object).success(function() {
        // the object was passed here
    });

}

这样可行,但我想知道这个案例是否适合$ q。

如果我使用$ q构造函数包装condition1

if (condition1) {
    return $q(function(resolve, reject) {
        // ajax success
        resolve(data);
    }
}

如何才能实现相同的功能,但只需拨打callServiceCreate() / Service.create()一次?

1 个答案:

答案 0 :(得分:1)

你可以在这里使用$q.when来传递promise when函数

<强>代码

function create() {
    var condition1Promise;
    if (condition1) {
        condition1Promise = callServiceCreate(object);
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    $q.when(condition1Promise).then(function(){
        Service.create(object).success(function() {
            // modify object here
            // the object was passed here
        });
    })
}

function callServiceCreate(object) {
    //returned promise from here to perform chain promise
    return Service.create(object).then(function(data) {
        // the object was passed here
        return data;
    });
}