Why can’t I get value returned by function?

Asked

Viewed 90 times

2

I can’t get the value returned from the function, what would be the reason? Someone could help me?

In my html page I have the following function:

function montarCursos(){
            var cursos = controller.getCursos();

            if(cursos != null){
                for(var i = 0; i < cursos.length; i++){
                    $("#cursos").append('<button class="ui-btn ui-corner-all" data-transition ="slide" onclick="controller.setNomeCurso("' + cursos[i].Value +'")">' + cursos[i].Name + '</button>')
                }
            }   
        }

Controller.js

var controller = {
getCursos: function () {

        function carregarCursos() {
            var resultado = [];
            var cursos = new cursosDao();
            resultado = cursos.getCursos();
            if (resultado.length > 0) {
                return resultado;
            } else {
                return null;
            }
        }
        loadDependence("Dao/cursosDao.js", carregarCursos);
    }
}

loadDependence.js:

function loadDependence(url, callback) {

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.onreadystatechange = callback;
    script.onload = callback;
    head.appendChild(script);
}

cursosDao.js

function cursosDao() {
    this.getCursos = function() {
        var cursos = [];
        cursos.push({
            "Value" : "Anáse de Sistemas",
            "Name" : "Anáse de Sistemas"
        });

        cursos.push({
            "Value" : "Ciência da Computação",
            "Name" : "Ciência da Computação"
        });

        return cursos;
    }
}
  • 2

    You’d better put the code here in place of a link to an external site.

  • Edited question, excuse me...

1 answer

4


The problem is that the return within the function carregarCursos applies only to carregarCursos. It will not "jump out" and serve to return a pro value getCursos. In the way your code is written, getCursos will always return undefined, without waiting for the courses to be loaded.

One way to check this is to put a console.log at the end:

getCursos: function () {
    /*...*/
    loadDependence("Dao/cursosDao.js", carregarCursos);
    console.log("Nao está esperando pelo loadDependence...");
    return 17; // E está chegando no final da função 
}

Unfortunately, you don’t have a pretty way of solving this problem in Javascript. You’ll have to do the getCursos use an API with callbacks instead of returning to the course list.

getCursos: function (onDone) {
    loadDependence("Dao/cursosDao.js", function() {
        var resultado = [];
        var cursos = new cursosDao();
        cursos.getCursos(function(resultado){
            if (resultado.length > 0) {
                onDone(resultado);
            } else {
                onDone(null);
            }
        });
    });
}

controller.getCursos(function(cursos){
  if(cursos != null){
    for(var i = 0; i < cursos.length; i++){
      /*...*/
    }
  }
}

In this example I also assumed that the cursos.getCursos may have to make an asynchronous request and therefore also need to return the value via callback. If you don’t need to request you can continue using the synchronous interface you were already using.

  • thank you very much for the reply, but even after the amendment unfortunately I still cannot get the returned value. Is there any other alternative to do all this? I would like to leave the project well structured for eventual maintenance.

  • Converting the code to use continuations instead of returns is something that will take work and is one of the biggest hassles of working with Javascript. And the result is really ugly. (Give a search for Promises and for generators if you want to tame the callbacks)

  • Thanks anyway, I’ll accept your reply. I was struggling not to put the script tags on the HTML page manually, I was leaving dynamic. But I think I’d better simplify my work.

  • If the problem is only the modules loaded on the page, it has tools like the Browserify that allow you to order the modules in your Javascript without having to add a lot of tags in html. Basically, it takes all the files you need and concatenates into an "archive" only.

Browser other questions tagged

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