gpt4 book ai didi

angularjs - AngularJS 中使用 Promise 和 Defer 进行同步和异步调用

转载 作者:行者123 更新时间:2023-12-02 10:21:27 26 4
gpt4 key购买 nike

我创建了以下 Controller ,其中有 2 个服务调用服务。第二个响应先于第一个响应。我想做的就像我需要第一个响应,然后第二个响应。但我只是坚持异步和同步请帮我解决。

第二次调用取决于第一次调用。例如,如果第一个调用返回 10 条记录,那么我必须调用第二个 Web 服务 10 次,从第一个响应中获取 id。所以我使用 for 循环,但它不正确。

Controller

var mycompaigndata = [];

asyncService.loadDataFromUrls($http.get(WSURL + 'api/first/',
{
headers:
{
"Authorization":'Bearer <my-token>'
}
}))
.then(function(data)
{
console.log(data);
});


asyncService.loadDataFromUrls($http.get(WSURL + 'api/second',
{
headers:
{
"Authorization":'Bearer <my-token>'
}
}))
.then(function(data)
{
console.log(data);
});

服务

app.service('asyncService', function($http, $q) 
{
return {
loadDataFromUrls: function(url)
{
var deferred = $q.defer();
var urlCalls = [];

urlCalls.push(url);

$q.all(urlCalls)
.then(
function(results)
{
deferred.resolve(results)
},
function(errors)
{
deferred.reject(errors);
},
function(updates)
{
deferred.update(updates);
});
return deferred.promise;
}
};
});

最佳答案

为了确保第一个调用完成后执行第二个调用,请将第二个调用放在第一个调用的 then 内。要根据第一次调用的结果数进行多个“第二次”调用,请使用 $q.all

asyncService.loadDataFromUrls('api/first/')
.then(function(firstData) {
//assuming firstData is an array of 'x' items, do a call for each of these items:
console.log('results of first call holds ' + firstData.length + ' items');
var promises = [];
for(var i = 0; i<firstData.length; i++){
var id = firstData[i].id;//you can use this to pass to the second call
promises.push(asyncService.loadDataFromUrls('api/second'));
}
return $q.all(promises);
})
.then(function(results) {
//'results' is an array of results, the nth item holds the result of the 'nth' call to loadDataFromUrls
for(var i = 0; i<results.length; i++){
console.log('result nr. ' + i + ' :' + results[i])
}
});

通过使用 return $q.all(promises),您可以避免厄运的 promise 金字塔,并保持扁平结构。

您的服务代码不再需要循环。作为旁注,您可以缩短服务的代码并避免使用“显式 promise 构造反模式”(请参阅​​ here ),如下所示:

app.service('asyncService', function($http, $q) 
{
return {
loadDataFromUrls: function(url)
{
return $http.get(WSURL + url, {
headers: {
"Authorization": 'Bearer <my-token>'
}
}).then(function(response){ return response.data; });
}
};
});

关于angularjs - AngularJS 中使用 Promise 和 Defer 进行同步和异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36736974/

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