简体   繁体   English

访问回调内的变量

[英]Accessing a variable inside a callback

I am in a react app and making a call using axios: 我在一个反应​​应用程序并使用axios打电话:

   import axios from 'axios';

    export default {
      getData : function(callback){

        var instance = axios.create({
          baseURL: '//abc/json',
          withCredentials: false
        });

        instance.get('')
            .then((response) => {              
                  callback(response.data.abc);                
              }, (error) => {
                  callback(error)
              });
         }
    }

In another file, I am doing the following: 在另一个文件中,我正在执行以下操作:

import file from './file';


//class definition...

    componentDidMount(){

        var obj = {}
        var res = file.getData(function(abc){
            obj['abc'] = abc;
        });

        console.log('obj-abc ', obj.abc); //returns undefined
      }

As shown above, I keep getting undefined. 如上所示,我一直未定义。 I basically, want the variable to be available globally. 我基本上希望变量在全球范围内可用。 I looked at other suggestions regarding callbacks on this site but none of them could help me. 我查看了有关本网站回调的其他建议,但没有一个可以帮助我。

Any help would be appreciated. 任何帮助,将不胜感激。

Simply put 简单的说

componentDidMount(){

var obj = {}
var res = file.getData(function(abc){
    obj['abc'] = abc;
    console.log('obj-abc ', obj.abc);
});

Since the getData method is asynchronous, it will not necessarily be executed sequentially in the javascript code. 由于getData方法是异步的,因此不一定在javascript代码中按顺序执行。 This variable is already global but if you want to make sure you can use it right after it, put some kind of completion condition before continuing code execution. 这个变量已经是全局的,但如果你想确保你可以在它之后立即使用它,那么在继续执行代码之前先放置一些完成条件。

Just to be clear on JS here. 在这里要清楚JS。 Look at code 看看代码

setTimeout(met1, 0);
console.log("11");    
setTimeout(met2, 0);
console.log("22");

Out put will be like this 出局将是这样的

11
22
met1 output
met2 output

So always keep in mind that async code will be executed in future and not in this moment. 所以请记住,异步代码将在未来执行,而不是在此刻执行。 Will save you a lot of time in debugging. 将为您节省大量的调试时间。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM