在过去的两天里,我一直在阅读有关承诺,回调和生成器的尝试,以了解如何从异步函数中设置值我可以在$ scope对象中使用它。
我不能得到承诺,然后解决var
,它只是返回承诺,而不是价值,这是它应该做的,据我所知。这是我认为也许发电机可能会有所帮助的地方?
那么,如何从一个异步功能设置var
,这样我可以在对象使用var
$scope.options_scn_cst
这是专门为nvd3,因为我想要做的,是要遍历来自回送功能Rpt_scn_cost_v
的结果找到最大值,然后将其设置为用于nvd3的yDomain: [min, max]
中Y轴的最大值。
我的代码现在看起来是这样的:
function maxYvalue2() {
return Rpt_scn_cost_v.find({filter: { where: {scenario_id: $stateParams.id}}}).$promise.then(function(response){
var maxYvalue = 0;
var currMaxYvalue = 0;
for (var i=0;i<response.length;i++) {
var currMaxYvalue = parseFloat(response[i].cur_cost) + parseFloat(response[i].tgt_cost);
if (currMaxYvalue > maxYvalue) {
maxYvalue = currMaxYvalue;
};
}
return maxYvalue;
console.log("yVal: ", maxYvalue)
});
};
var mxY = 100000 // <======== when I set it to this maxYvalue2(), it resolves in a promise
console.log('var', mxY)
$scope.options_scn_cst = {
chart: {
type: 'lineChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 40,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: true,
dispatch: {
stateChange: function(e){ console.log("stateChange"); },
changeState: function(e){ console.log("changeState"); },
tooltipShow: function(e){ console.log("tooltipShow"); },
tooltipHide: function(e){ console.log("tooltipHide"); }
},
xAxis: {
axisLabel: '',
tickFormat: function(d) { return d3.time.format('%b %y')(new Date(d)); }
},
yDomain: [0, mxY], // <============ I then set mxY here in the $scope object
yAxis: {
axisLabel: '$/month',
tickFormat: function(d){
return d3.format('$,.0f')(d);
},
axisLabelDistance: -10
},
callback: function(chart){}
},
title: {
enable: true,
text: 'Scenario Costs Over Time'
},
subtitle: {
enable: false,
text: 'Put your Subtitle here.',
css: {
'text-align': 'center',
'margin': '10px 13px 0px 7px'
}
},
caption: {
enable: false,
html: 'Put your Caption Here.',
css: {
'text-align': 'justify',
'margin': '10px 13px 0px 7px'
}
}
};
,然后我把这样的$范围对象,然后:
<nvd3 data="data_scn_cst" options="options_scn_cst"></nvd3>
我想这样也使用$ Q,但它回复承诺,而不是价值太...
function maxYvalue2() {
var deferred = $q.defer();
Rpt_scn_cost_v.find({filter: { where: {scenario_id: $stateParams.id}}}).$promise.then(function(response){
var maxYvalue = 0;
var currMaxYvalue = 0;
for (var i=0;i<response.length;i++) {
var currMaxYvalue = parseFloat(response[i].cur_cost) + parseFloat(response[i].tgt_cost);
if (currMaxYvalue > maxYvalue) {
maxYvalue = currMaxYvalue;
};
}
deferred.resolve(maxYvalue)
console.log("yVal: ", maxYvalue)
});
return deferred.promise
};
var mxY = maxYvalue2() // <======== when I set it to this maxYvalue2(), it resolves in a promise
console.log('var', mxY)
谢谢sooo多!工作! – user2061886
这里也有一个问题......我将如何使用生成器代替或承诺? – user2061886