gpt4 book ai didi

javascript - 如何在 Angular 中掌握这个条件 promise ?

转载 作者:行者123 更新时间:2023-12-03 06:02:11 24 4
gpt4 key购买 nike

我必须解决 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);
});

关于javascript - 如何在 Angular 中掌握这个条件 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39710441/

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