问题
I am working on the the following function, and I want to make sure that the function returns after all these lines have been executed:
var cinfo = iClassInfo.instance().iClassById(nObject.dclass, true);
Right now the function returns without executing this line, and hence nObject.mClassName is always undefined. Thanks in advance!!
getObj : function(options) {
var self = this,
$master = $.Deferred(),
$deferreds = [];
return self._wt.getIterativeResults({
storage: self._str,
resSetName: self._resultSetName,
startIndex: options.startIndex,
endIndex: options.endIndex,
idForm: 1
}).then(
function(objects){
var nObjects = [];
$.each(objects, function(i,object){
var nObject = object.nObject;
if(nObject.dclass != null) {
var $deferred = iClassInfo.instance().$intializedDef;
$deferreds.push($deferred);
$deferred.done(function(deferreddone){
var cinfo = iClassInfo.instance().iClassById(nObject.dclass, true);
if(cinfo != null) {
nObject.mClassName = cinfo.name;
}
});
}
nObject.pp = object.npp;
nObjects.push(nObject);
});
$.when($deferreds).done(function(){
$master.resolve(nObjects);
});
return $master.promise();
},
function(resp) {
}
);
},
回答1:
There is a problem in how you were using the $deferreds
array with $.when()
so try
getObj: function (options) {
var self = this,
$master = $.Deferred(),
$deferreds = [];
return self._wt.getIterativeResults({
storage: self._str,
resSetName: self._resultSetName,
startIndex: options.startIndex,
endIndex: options.endIndex,
idForm: 1
}).then(function (objects) {
var nObjects = [];
$.each(objects, function (i, object) {
var nObject = object.nObject;
if (nObject.dclass != null) {
var $deferred = iClassInfo.instance().$intializedDef;
$deferreds.push($deferred);
$deferred.done(function (deferreddone) {
var cinfo = iClassInfo.instance().iClassById(nObject.dclass, true);
if (cinfo != null) {
nObject.mClassName = cinfo.name;
}
});
}
nObject.pp = object.npp;
nObjects.push(nObject);
});
//there was a problem here
$.when.apply($, $deferreds).done(function () {
$master.resolve(nObjects);
});
}, function (resp) {
$master.reject();
});
return $master.promise();
}
来源:https://stackoverflow.com/questions/23668442/jquery-return-from-function-after-completing-deferred