0

I'm handling with a "Switch" diferent actions. In this case Im trying to add to the variable "data" just one product into a Json object. The function giveMeProd.. should return the value.

case "pvc":
        if (option == 1) { //1 means I want a single prod.
            data = giveMeTheProductPlease(sessionStorage.baseId);
            console.log("result: " + data); ...

The giveMeTheProduct function:

    function giveMeTheProductPlease(id) {
    var aux = null;
    $.getJSON("./data/results.json", function (data) {

        var l = Object.keys(data).length;
        for (var i = 0; i < l; i++) {
            if (data[i].id == id) {
                console.log(data[i]);
                aux = data[i];

            }
        }
    })
    return aux;
}

I have been reading about the matter, it seems Im trying to run a asyncronous function and return it into an syncronous function. It could be solved with a "callback", but I need to recieve the "id" parameter and I dont know how to do it.

Any idea?

javialm
  • 1
  • 1

1 Answers1

0

Your function giveMeTheProductPlease() is dealing with asynchronous code. It actually returns null before the request made with $.getJSON has a chance to finish.

Here what you could do:

 var findProduct = function(id, data) {
     var aux = null;
     for (var i = 0; i < data.length; i++) {
         if (data[i].id === id) {
             aux = data[i];
        }
    }

     return aux;
 }

 $.getJSON("./data/results.json", function (result) {
     switch(val) {
     case "pvc":
         if (option == 1) { //1 means I want a single prod.
             data = findProduct(sessionStorage.baseId, result);
         }
 })
flocks
  • 218
  • 2
  • 13