javascript - JS中无法访问函数作用域之外的变量

标签 javascript scope

很抱歉这个菜鸟问题,但我一直在搜索有关影子变量的所有现有答案,但仍然无法使我的代码工作

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/

相关文章:

for-loop - Shopify:如何在循环外获取forloop.index的值?

javascript - 如何将 Backbone 模型与 jQuery 相关的范围一起使用

javascript - 无法使用 $pull (Mongoose) 删除用户模型数组中的对象

javascript - Microsoft Edge : window. 打开仅在第一次尝试时才能正常工作

javascript - Angular JS将2个对象合并到第三个对象中

C++/结构范围

c++ - 立即传递其成员时的右值范围

javascript - 添加 "submit()"时 ng-show/ng-hide 循环,导致浏览器崩溃

javascript - 当输入字段具有特定值时,如何更改 div 的类?

scope - 与 sbt 中的 `{.}/*:name` 和 `*/*:name` 的区别?