Hello.

Faced a small puzzler. Tell me, please, how to return the value to the function? Here is a sample code:

var searchSku = function(val){ var path = "/search.json?q=", sku = val; jQuery.ajax({ url: path + val, type: 'get', dataType: 'json', success: function($data) { var b = $data.id; //тут мы получаем значение }, }); // как вернуть это значение? return }; 

Reported as a duplicate by participants Alexey Shimansky , Darth , pavel , user207618, AK 24 Jul '17 at 7:31 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    Because The answer comes in JSON format, first you need to parse it using JSON.parse .

     var searchSku = function(val) { var path = "/search.json?q="; return jQuery.ajax({ url: path + val, type: 'get', dataType: 'json', success: function($data) { var deferred = $.Deferred(); switch (data.code) { case 200: deferred.resolve((JSON.parse($data)).id); break; default: deferred.reject(); break; } return deferred.promise(); } }); }; 

    Using:

     $.when(searchSku("text")) .then( function(data){ alert(data); // $data.id }); 
    • Thanks for the answer, but you need to return to the searchSku () function, in this example, return returns to the child function only - Victor
    • @Victor It is impossible to return a function, it can only be returned as the result of a function. Completed the answer with work with promises , perhaps in this style the function will be more convenient to work with. - Pavel Dmitrenko
    • Thank you very much! - Victor

    use async: false and good old eval

     var searchSku = function(val){ var path = "/search.json?q=", sku = val, b; $.ajax({ url: path + val, type: 'get', dataType: 'json', async:false, success: function(data) { b = eval('('+data+')'); //тут мы получаем значение }, }); // просто возвращаем return b.id; };