-1

I have this code:

$(document).ready(function(){
    var dsg =  new contract('1', '/json/dsgABI.json');
    console.log(dsg.data);
});
var contract = function(contractAddress, abiFile){
    var data = new Object();
    $.when(abi()).then(function(abi) {
        data.abi = abi;
    });
    function abi(){
        return $.getJSON(abiFile, function(abi){
            return abi;
        });
    }
    this.data = data;
}

But when a use console.log(dsg.data.abi[0]) I get undefined.

Can you help me write code that allows me to call the data array both inside and outside the function, and in the array there were results of the function.

P.S.: async function will be 10 or more! And I need push results onto an array and use it when I need!

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Do you understand the meaning of *asynchronous*? What happens right after an async call is made? – PM 77-1 Jan 02 '19 at 17:32
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Jan 02 '19 at 18:07

1 Answers1

0

You need to return a promise with the resolved value you want to access. It's simpler than you are doing.

You call your function contract which performs the async request and returns a promise with the fetched data, and then you access this data when resolved.

So your code should look something like:

$(document).ready(function(){
    contract('1', '/json/dsgABI.json').then(data => {
      console.log(data);
    });
});
function contract(contractAddress, abiFile){
    return $.getJSON(abiFile, abi => abi);
}
quirimmo
  • 9,800
  • 3
  • 30
  • 45