Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery
I need a prototype of chart with constructor, so I wrote this:
function Chart(file) {
var chart = undefined
$.getJSON(file, function(data) {
chart = {
categories: data.keys
series: [{
name: 'first',
data: data.first
}, {
name: 'second',
data: data.second
}]
}
});
return chart
}
Then I realized, that because of JaavScript's synchronousness it returns undefined
. How should I defere the return statement of Chart
?
A defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
The use of defer in the first line of the main function causes that statement to be postponed until the end of the function. Hence, it is executed in the last.
In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns. In simple words, defer will move the execution of the statement to the very end inside a function.
Defer is used to ensure that a function call is performed later in a program's execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages. package main.
function Chart(file, callback) {
var chart = undefined
$.getJSON(file, function(data) {
chart = {
categories: data.keys
series: [{
name: 'first',
data: data.first
}, {
name: 'niewykopane',
data: data.first
}]
}
callback(chart);
});
}
You could use $.ajax()
and set the async
property to false
.
Warning: This method is not recommended! It blocks the whole UI, all other JavaScript and timers until the request is finished!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With