0

Why does my loop return 3 for the length of an array, but the callback function searchKey(value).length returns 0?

     function searchKey(value) { 
        if (value.length > 0) {
            var keys = getKeys(value);// return array string
            var arr = [];
            $.post('@Url.Content("~/Home/GetJsonData")', {}, function (result) {

                $.each(eval(result.replace(/[\r\n]/, "")), function (index, item) {
                    if (item.Tag != null) {
                        for (var i = 0; i < keys.length; i++) {

                            if (item.Tag.toLowerCase().indexOf(keys[i]) > -1) {

                                arr.push({
                                    "Key": item.Key,
                                    "Value": item.Tag,
                                    "Tag": keys[i],
                                    "Length": keys[i].length

                                });
                                alert("arr:" + arr.length);// result: 3
                                break;
                            }
                        }
                    }
                });                   
            }, "json");
        }
         alert("arr:" + arr.length);// result: 0
        return arr;
}

    function getKeys($param) {
        //some code to find 'keys'
        return keys;
    }
joe_young
  • 4,107
  • 2
  • 27
  • 38
Sonvu
  • 1
  • 1

1 Answers1

0

jquery post/get request are asynchronous. Your function makes post request, finished, return empty array, and then the response from server came back to client. You can make it synchronized (https://stackoverflow.com/a/5821467/5206593) but this is not good idea, because your page will be slow.

Community
  • 1
  • 1
michal pavlik
  • 330
  • 3
  • 18