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 })
}
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
thatasync: false
. And " pass the target object as function argument" not quite what happens there, thatfunction(data)
is the return of a Promise, an asynchronous code, a concept similar toThread
andTask
in thec#
– Ricardo Pontual
the comment was over, if you need more clarification I can write a reply with this and more details
– Ricardo Pontual
I get it, @Ricardopunctual, thank you so much for directing.
– fnatans
@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.
– fnatans
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?
– Ricardo Pontual