很抱歉这个菜鸟问题,但我一直在搜索有关影子变量的所有现有答案,但仍然无法使我的代码工作
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!");
})
}
}
});
我尝试了很多方法,但仍然无法将模型记录属性存储到变量中并从 $.post
有效负载访问
最佳答案
要继续使用变量新值,您必须将代码放入 Promise then
中。然后它就可以工作了:
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
方法请求结束之前被调用,即使它是在其中调用的第一个方法。
更新:
我不明白你对 product, 1
的这两个 find
方法的意思,但是:
如果请求中有两个值要发送到帖子,则应仅使用
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 }) }); });
关于javascript - JS中无法访问函数作用域之外的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25059742/