Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defering return statement [duplicate]

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?

like image 867
ciembor Avatar asked Nov 20 '11 14:11

ciembor


People also ask

Does defer run after return?

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.

Where should we use * Defer * In the following code?

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.

What is the point of Defer in go?

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.

What is defer programming?

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.


1 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 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!

like image 117
ComFreek Avatar answered Sep 21 '22 04:09

ComFreek