gpt4 book ai didi

javascript - AngularJS : calling a factory method within the loop

转载 作者:行者123 更新时间:2023-11-28 00:00:49 24 4
gpt4 key购买 nike

我有一个工厂方法,如下所示:

angular.module('GridSamplesApp')
.factory('registerPostFactory', function($resource, $q, WebRequest) {
var getMessage = function(Upddata, token, dataurl)
{
var deferred = $q.defer();
var settings = {
data: Upddata,
headers: {
'Content-Type': 'application/JSON',
'x-csrf-token' : token
},
method: 'POST',
url: dataurl,
withCredentials: true
};
WebRequest.requestRaw(settings).then(
function(response) {
// data from app sec

var msg = response;

deferred.resolve(msg);
},
function(error) {
console.log('Error retrieving message', error);
deferred.reject('Error retrieving message', error);
});

return deferred.promise;
};


return {
getMessage: getMessage
};
});

我有一个看起来像的 Controller

$scope.getLogs = function()
{

$.each($scope.modifiedSN, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});

$scope.inputs.push({SN:'', Key:'', status:'', log:''});
for(var i=0; i<result.length; i++)
{
var j = result[i];
if ($scope.data[j].SerialNumber !== "")
{


var Upddata = {};
Upddata['IConvRuleFlg'] = '';
Upddata['SrNum'] = $scope.data[j].SerialNumber;
Upddata['LvEmailId'] = 'abc@xyz.com';
Upddata['WKey'] = $scope.data[j].WtyKey;

registerPostFactory.getMessage(Upddata, $scope.token, dataurl).then(
function(response) {
$scope.msg = response.headers["custommessage"];
$scope.data[j].AutolinkErrorlog = $scope.msg;
$scope.inputs.push({SN: $scope.data[j].SerialNumber, Key: $scope.data[j].WtyKey, status: response.headers["msgtype"], log: $scope.msg});
},
function(error) {
console.log('Error reading msg: ', error);
}
);
}
}

};

问题在于,它只获取数组中的最后一个元素,因为它是异步调用,并且循环不会等待响应,我尝试使用 $q.all()但不知道如何实现这一点,有人可以帮忙吗?

最佳答案

据我了解,你的工厂工作正常,就像@RaviMone所说,通过在for循环中使用异步回调代码,你会惊讶地发现初学者经常陷入这个陷阱。另外,我看到一个 $scope.msg,不确定它来自哪里以及它如何工作,但由于调用的异步和并行性质,它可能会显示各种调用的错误值,如果每次调用都会发生变化,您应该考虑序列化您的调用。

更简洁的编写 $scope.getLogs 的方法可能是(我减少了 jQuery 的使用,使用了 ES5 的东西,如果你必须支持遗留系统,你可以使用 this ):

$scope.getLogs = function(){
var result = [] // again not sure where the result comes from, so initizing it here, else you can append filtered array to the previous set
$scope.modifiedSN.forEach(function(value) {
if (result.indexOf(value) < 0) result.push(e);
});
$scope.inputs.push({SN:'', Key:'', status:'', log:''});

var promises = result.map(function(val){
return $scope.data[val];
}).filter(function(val){
return val && val.SerialNumber !== ""; // first check if $scope.data[j] exists
}).map(function(val){
return registerPostFactory.getMessage({
IConvRuleFlg: '',
LvEmailId: '',
WKey: val.WtyKey,
SrNum: val.SerialNumber
}).then(function(response){
$scope.msg = response.headers["custommessage"];
val.AutolinkErrorlog = $scope.msg;
$scope.inputs.push({SN: val.SerialNumber, Key: val.WtyKey, status: response.headers["msgtype"], log: $scope.msg});
}).catch(function(e){
console.log('Error reading msg: ', e);
});
});

$q.all(promises)
.then(function(resArray){
console.log('get all logs...');
}).catch(function(e){
console.log('some error: ', e);
});
};

编辑:

如果您希望它们按顺序完成:

$scope.getLogs = function(){
var result = [] // again not sure where the result comes from, so initizing it here, else you can append filtered array to the previous set
, serialPromise = $q.when(1); // just initializing a promise.
$scope.modifiedSN.forEach(function(value) {
if (result.indexOf(value) < 0) result.push(e);
});
$scope.inputs.push({SN:'', Key:'', status:'', log:''});

result.map(function(val){
return $scope.data[val];
}).filter(function(val){
return val && val.SerialNumber !== ""; // first check if $scope.data[j] exists
}).forEach(function(val){
var datum = {
IConvRuleFlg: '',
LvEmailId: '',
WKey: val.WtyKey,
SrNum: val.SerialNumber
};
serialPromise = serialPromise.then(function(){ // adding a new promise to the chain.
return registerPostFactory.getMessage(datum);
}).then(function(response){
$scope.msg = response.headers["custommessage"];
val.AutolinkErrorlog = $scope.msg;
$scope.inputs.push({SN: val.SerialNumber, Key: val.WtyKey, status: response.headers["msgtype"], log: $scope.msg});
}).catch(function(e){
console.log('Error reading msg: ', e);
});
});

serialPromise.then(function(){
console.log('got all logs...');
}).catch(function(e){
console.log('some error: ', e);
});
};

关于javascript - AngularJS : calling a factory method within the loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31831663/

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