Javascript 返回的未定义变量
我正在编写一个Javascript函数,它将返回一个数字作为结果。这是我的代码:Javascript 返回的未定义变量,javascript,undefined,Javascript,Undefined,我正在编写一个Javascript函数,它将返回一个数字作为结果。这是我的代码: get_tiquete_hacienda: function (){ var myconsecutivo = 0; var rpc2 = require('web.rpc'); rpc2.query({ model: 'pos.order', method: 'compute_sales_bsi'
get_tiquete_hacienda: function (){
var myconsecutivo = 0;
var rpc2 = require('web.rpc');
rpc2.query({
model: 'pos.order',
method: 'compute_sales_bsi'
}).then(function(res) {
myconsecutivo = res;
console.log('soy el otro: ' + myconsecutivo);
});
return myconsecutivo;
}
如果我看一下控制台,soy el otro:将呈现正确的值
但是返回myconsecutivo是未定义的
为什么会出现这种情况?您需要在“then”语句中返回值
get_tiquete_hacienda: function (){
var myconsecutivo = 0;
var rpc2 = require('web.rpc');
return rpc2.query({
model: 'pos.order',
method: 'compute_sales_bsi'
}).then(function(res) {
myconsecutivo = res;
console.log('soy el otro: ' + myconsecutivo);
return myconsecutivo;
});
}
get_tiquete_hacienda().then(function (myconsecutivo) {
// myconsecutivo is correct here
});
或者更简洁地说:
get_tiquete_hacienda: function (){
var rpc2 = require('web.rpc');
return rpc2.query({
model: 'pos.order',
method: 'compute_sales_bsi'
}).then(function(res) {
console.log('soy el otro: ' + res);
return res;
});
}
get_tiquete_hacienda().then(function (myconsecutivo) {
// myconsecutivo is correct here
});