这个箱子适合q美元吗

Would this case be a good fit for $q?

本文关键字:美元 箱子      更新时间:2023-09-26

我很难确定是否应该在以下psuedo编码的场景中使用$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()一次的情况下实现相同的功能?

您显然可以在这里使用$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;
    });
}