如何在角度上掌握这种有条件的承诺?
我必须解决angularjs
中的一个问题,并且我现在停留了几个小时。如何在角度上掌握这种有条件的承诺?
,如果有这样的伪代码:
doSomething(param){
var res;
if(param = "ok"){
//do some api calls with promise
res = promise result
}
doSomeStuff(){
//if i got res variable, continue with this...
// else
//if res is not set, do this...
}
所以我的问题是:我怎么能这样做? doSomeStuff
函数需要知道,如果变量res
设置或不。因此,如果未设置变量res
,则需要等待或继续。
从角度使用“然后”因此,一旦承诺得到解决,你可以检查数据的承诺回来,如果你只需要一个API调用执行你的逻辑
:使用$ HTTP的then()
doSomething(param){
if(param == "ok"){
//do some api calls with promise
$http({
method: 'GET',
url: url
}).then(
function success(response) {
doSomeStuff(response);
},
function error(response) {
console.log(response);
}
);
}
}
如果您需要进行许多API调用:
var doSomething = function (param){
if(param == "ok"){
// imagine that listeUrl is an array of url for api calls
var promises = [];
for (var i in listeUrl) {
promises.push(//Push the promises into an array
$http({
method: 'GET',
url: listeUrl[i]
}).then(function success(response) {
return response.data;
})
);
}
return $q.all(promises); // Resolve all promises before going to the next .then
}
}
doSomething("ok").then(function(res){
doSomeStuff(res);
});
你需要做一个或多个API调用吗? – AlainIb
请注意'if(param =“ok”)'不是一个比较,而是一个任务 – charlietfl
@charlietfl哦是啊谢谢我复制粘贴太快 – AlainIb
把'doSomeStuff'代码在'then'你的承诺。除去'res'变量,promise本身应该返回一个set/unset值,你可以使用它来在'doSomeStuff'中分支。 – nem035
[JavaScript isset()等效]的可能的重复(http://stackoverflow.com/questions/2281633/javascript-isset-equivalent) – darham
@darham几乎不是这个问题的重复。这个问题也涉及到异步。 – nem035