JS - Target object as function argument

Asked

Viewed 31 times

0

I come from C# and I’m having a hard time understanding this concept of passing the target object as a function argument.

In the examples below, the first works, as I do to assign the function result to the object without having to open a new scope?

function loadData(){

    $.getJSON('json/acompFatAutomatico.json', function(data) {          
        alert(data[0].Codigo);
    });
}


function loadData(){

    var data = $.getJSON('json/acompFatAutomatico.json');
    alert(data[0].Codigo);

}

  • is trying to use an asynchronous method synchronously, if you do not know these concepts study what they are. Make this code synchronously without Promise going block off the code until it has the result, which is a lousy user experience, have your browser locked. If you still want to, pass as parameter on getSON that async: false. And " pass the target object as function argument" not quite what happens there, that function(data) is the return of a Promise, an asynchronous code, a concept similar to Threadand Task in the c#

  • the comment was over, if you need more clarification I can write a reply with this and more details

  • I get it, @Ricardopunctual, thank you so much for directing.

  • @Ricardopunctual, what is the correct term for this type of writing? I really need to study this way of passing another function as an argument.

  • in the first example Function expects the return of a Promise, which is the return of the asynchronous call, but can also be called callback. These two questions address this, it is a good reading: https://answall.com/questions/398821/retornar-valor-de-promise? https://answall.com/questions/168824/diferen%C3%a7a-entre-Promise-e-callback?

1 answer

0

That function getJSON, apparently, it takes 2 parameters: a string (route to fetch data), and another function to manipulate the data obtained. That is, if it already uses another function to manipulate the data, there is no reason for it to return this data "directly", so the second example ends up not working.

When a function is used as a parameter of another, we call it a "function of Callback".

If you want to manipulate the obtained data, regardless of the manipulation (in the specific case, just insert the value into another variable) you must place this manipulation within the Callback, as already done in the first case. However you have more means to do this, as using Arrow Functions.


Some examples:

function loadData1(){
  let myData

  $.getJSON('json/acompFatAutomatico.json', function(data) {
    myData = data
  })
}

function loadData2(){
  let myData
    
  function setMyData(data) {
    myData = data
  }

  $.getJSON('json/acompFatAutomatico.json', setMyData)
}

function loadDataComArrowFunction(){
  let myData

  $.getJSON('json/acompFatAutomatico.json', (data) => { myData = data })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.