Javascript Can';t访问JS中函数范围之外的变量
很抱歉提出这个noobie问题,但我一直在搜索有关隐藏变量的所有现有答案,但仍然无法使我的代码正常工作Javascript Can';t访问JS中函数范围之外的变量,javascript,scope,Javascript,Scope,很抱歉提出这个noobie问题,但我一直在搜索有关隐藏变量的所有现有答案,但仍然无法使我的代码正常工作 export default Ember.ArrayController.extend({ actions: { generateInvoice: function() { var amount1; // declare a variable var amount2; this.store.fi
export default Ember.ArrayController.extend({
actions: {
generateInvoice: function() {
var amount1; // declare a variable
var amount2;
this.store.find('product', 1).then(function(obj){
amount1 = 100; //assign value to the amount variable
});
this.store.find('product', 2).then(function(obj){
amount2 = 200;
});
console.log(amount1); // undefined!
console.log(amount2); // undefined!
$.post('http://nzud.co.nz/invoice',{
foo1: amount1, //access variable amount ---doesn't work!!
foo2: amount2
} ).done(function(data){
alert("success!");
})
}
}
});
我已经尝试了很多方法,但仍然无法将model record属性存储到变量中并从
$访问。post
有效负载要继续使用变量新值,您必须将代码放入promisse中,然后。然后它就会起作用:
export default Ember.ArrayController.extend({
actions: {
generateInvoice: function() {
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount
}).done(function(data){
alert("success!");
})
});
}
}
});
发生这种情况是因为方法find
是异步的,因此您必须在回调函数中处理其结果,在本例中是函数then
。generateInvoice
范围内的所有内容(可能)都将在find
方法请求结束之前被调用,即使它是在其内部调用的第一个方法
更新:
我不明白你对产品1的这两个查找方法的意思,但是:
- 如果要发送到post的请求中有两个值,则应仅使用
find()
方法一次:
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount,
bar: another_value
})
});
- 或者,如果必须调用两个不同的
find
方法,则必须将它们链接起来:
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
this.store.find('product', 1).then(function(obj){
var another_amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount,
bar: another_amount
})
});
});
申报超出您职能范围的金额:
var amount; // declare a variable
export default Ember.ArrayController.extend({
actions: {
generateInvoice: function() {
this.store.find('product', 1).then(function(obj){
amount = 100; //assign value to the amount variable
});
console.log(amount) // undefined!
$.post('http://nzud.co.nz/invoice',{
foo: amount, //access variable amount ---doesn't work!!
} ).done(function(data){
alert("success!");
})
}
}
});
此.store.find
为asynchronous@adeneo谢谢你指出这一点。我需要了解更多关于Promise的信息这可能会调用未定义的amount
的post函数。不确定你的意思,但是我错过了异步部分。在运行post函数时,Amount仍然没有值。这正是我的意思。感谢您的快速回答。我只是更新我的问题,实际上有两个记录查询承诺,所以我不能将$.post
放入其中一个these@mko您必须在post请求中一次性发布这两个值?是的,$.post中的有效负载包含两个ASIC记录查询中的两个值。对于输入错误,第二个是store.find('product',2)
@mko在这种情况下,是的。你别无选择。所以你在另一个请求完成后开始一个新的请求,等等。。。