Disabling the return statement

Possible duplicate:
JavaScript asynchronous return value / destination using jQuery

I need a prototype diagram with a 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 due to the synchronization of JaavScript, it returns undefined . How should I defer a Chart return statement?

+4
source share
2 answers

1.) Specify a callback function

 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); }); } 

2.) Synchronous request (not recommended!)

You can use $.ajax() and set the async property to false .

Warning: This method is not recommended! It blocks the entire user interface, all other JavaScript and timers, until the request is complete!

+6
source

JavaScript supports closures :

 function Chart(file, callback) { var chart = undefined; $.getJSON(file, function(data) { chart = { categories: data.keys, series: [{ name: 'first', data: data.first }, { name: 'seconde', data: data.second }] } callback(chart); }); } // Usage: Chart('some/file.txt', function(chart) { // do something with chart }); 

In fact, you are using closure by calling $.getJSON() .

+4
source

Source: https://habr.com/ru/post/1382145/


All Articles