我有一个函数返回一个承诺(我相信,我是新来的JavaScript),我试图设置一个变量mxY
。我写我的功能是这样的:设置对外部变量的承诺
function maxYvalue2() {
return Rpt_scn_cost_v.find({filter: { where: {scenario_id: $stateParams.id}}}).$promise.then(function(response){
var maxYvalue = 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
};
}
console.log("yVal: " + maxYvalue)
return maxYvalue;
});
};
var mxY = maxYvalue2().then(function (response) {
console.log("fnc: ", response);
return response;
});
console.log(mxY);
和我的控制台显示这一点,在那里mxY
似乎登录一个{$$state: Object}
:
reports.controller.js:99 d {$$state: Object}
$$state: Object
status: 1
value: 78820.3574413
__proto__: Object
__proto__: Object
reports.controller.js:88 yVal: 78820.3574413
reports.controller.js:94 fnc: 78820.3574413
从迄今我了解,在maxYvalue2()
的.then
正在恢复一个承诺,这就是为什么我回到$$state.Object
,但我需要做的是“解开”的承诺,当它解决,是正确的还是我完全在这里?然后我将它设置为变量?
------编辑---------
我试图让maxYvalue2()
结果去这里...在下面的高亮区域更改yDomain: [0, 100000]
到yDomain: [0, mxY]
:
function maxYvalue2() {
return Rpt_scn_cost_v.find({filter: { where: {scenario_id: $stateParams.id}}}).$promise.then(function(response){
var maxYvalue = 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
};
}
console.log("yVal: " + maxYvalue)
return maxYvalue;
});
};
var mxY = maxYvalue2().then(function (response) {
console.log("fnc: ", response);
return response;
});
console.log(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, 100000], //<======change the 100000 to the var mxY
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'
}
}
};
“unwrap”是什么意思?你的诺言和console.log似乎显示了期望值。 – tsuz
移动所有需要'then'回调中的值的代码。这是“解开”它的唯一方法。 – Bergi
ok ...所以我移动了'then()'中的'$ scope.options_scn_cst',但现在好像我现在不能访问'$ scope.options_scn_cst' ... – user2061886