我无法确定是否应该将 $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
});
}
注意:condition1
和condition2
是互斥的。
以前,我做了这样的事情:
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;
});
}
关于javascript - 这种情况适合 $q 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31081689/