Return of a simple javascript function not working

Asked

Viewed 91 times

0

I have the code snippet below that performs a call to the method findCustomers(term, isNumber));

if(isSequenceNumber(term) && term.length >= 6){
    var data = findCustomers(term, true);
    console.log(data);
    response(data);
}else{
    var data = findCustomers(term, false);
    console.log(data);
    response(data);
}

The method that is not returning anything is below:

function findCustomers(term, isNumber){
    $.ajax({
        url: appContext + "/auth/search-customer-by-service",
        type: "GET",
        contentType: "application/json",
        dataType: 'json',
        data: {
            term: term,
            isNumber: isNumber
        },
        success: function(data) {
            if (data.length > 0) {
                // Com resultados de clientes.
                var customerArray = new Array(data.length);
                var i = 0;
                data.forEach(function(entry) {
                    var newObject = {
                        label: entry.fullName + " " + "[" + entry.email + "]",
                        idCustomer: entry.idCustomer,
                        hasAvailableService: entry.hasAvailableService,
                    };
                    customerArray[i] = newObject;
                    i++;
                });
                return customerArray;
            } else {
                // Sem resultados de clientes.
                var notFoundArray = new Array(1);
                var notFoundObject = {
                        label: "Nenhum cliente encontrado",
                        idCustomer: 0,
                        hasAvailableService: "",
                };
                notFoundArray[0] = notFoundObject;
                return notFoundArray;
            }
        }
    });
}

It is worth noting that the request made by AJAX returns concrete data, but the return in the call of the function is always being undefinied

EDITED

After understanding the nature of the problem according to the answers proposed below I called the function in which performs the AJAX request via anonymity function in this way:

findCustomers(term, true, function(response){
    console.log(response);
    response(response);
});

But I still haven’t succeeded.

  • 1

    I believe it’s being returned undefined for the function $.ajax is asynchronous, ie is not executed on time. In this case, the return really is nothing. What you should have was a callback within success of your ajax where you perform the function with the results. In this case, your function $.ajax is called and returned at the same time but the return of the success does not return to anything since it is a callback. You can try to put the parameter async as false. See here

  • In fact, I was wrong in the words. It is not that it is not executed on time but rather the result you expect is not immediate.

  • @Kevinkouketsu, no doubt the problem is this. But unfortunately the solution of async in my case did not work.

  • @fernandosavio, indeed the nature of the problem and the same. Thank you

  • To create an ajax request, if/Else is inside another function?

1 answer

1


Do it this way:

if(isSequenceNumber(term) && term.length >= 6){
    var data = findCustomers(term, true, resultado);
}else{
    var data = findCustomers(term, false, resultado);
}

function resultado(data) {
    console.log(data);
    response(data);
}

function findCustomers(term, isNumber, resultado){
    $.ajax({
        url: appContext + "/auth/search-customer-by-service",
        type: "GET",
        contentType: "application/json",
        dataType: 'json',
        data: {
            term: term,
            isNumber: isNumber
        },
        success: function(data) {
            if (data.length > 0) {
                // Com resultados de clientes.
                var customerArray = new Array(data.length);
                var i = 0;
                data.forEach(function(entry) {
                    var newObject = {
                        label: entry.fullName + " " + "[" + entry.email + "]",
                        idCustomer: entry.idCustomer,
                        hasAvailableService: entry.hasAvailableService,
                    };
                    customerArray[i] = newObject;
                    i++;
                });
                resultado(customerArray);
            } else {
                // Sem resultados de clientes.
                var notFoundArray = new Array(1);
                var notFoundObject = {
                        label: "Nenhum cliente encontrado",
                        idCustomer: 0,
                        hasAvailableService: "",
                };
                notFoundArray[0] = notFoundObject;
                resultado(notFoundArray);
            }
        }
    });
}

That is, your result function will actually have what will be done, being a callback only when success of your request $.ajax is called.

PS: Maybe the syntax isn’t perfect because I wrote it right here in the O.R., but I think it’s gonna work.

If you weren’t going to create a new array within Success, you could just swap that whole function for success: resultado that would give in the same. You can do such a routine within your function too, there it is with you.

A good reference: What is a callback?

  • 1

    Perfect Kevin. In fact this is what I needed. The link was also of great help. Thank you

Browser other questions tagged

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