gpt4 book ai didi

javascript - 这种情况适合 $q 吗?

转载 作者:行者123 更新时间:2023-11-30 00:26:56 25 4
gpt4 key购买 nike

我无法确定是否应该将 $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;
});
}

关于javascript - 这种情况适合 $q 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31081689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com