Receive result of an ajax as return

0

Within the following scenario:

funcao1 = function() {
    $.ajax({
        success: function(data) {
                     return data;
                 }
    });   
}

funcao2 = function() {
    var dados = funcao1();
}

Is it possible to receive, even through promises, the ajax result of funcao1 in funcao2 ?

    
asked by anonymous 08.11.2018 / 19:08

3 answers

1

Can you use async / await? If you can, it's simple, see:

var funcao1 = async function() {
        var result
    var ajax = await $.ajax({
            url: 'https://api.nulbox.com',
        success: function(data) {
          result = data
        }
    });
    return result
}

var funcao2 = async function() {
    var dados = await funcao1();

    console.log(dados)
}

funcao2()
  

See the example working    here .

    
08.11.2018 / 19:56
2

I recommend using the Adrian solution, for using the newest ES7 API, with async/await .

But you can also do this by creating a Promise style ES6, see how it would look:

funcao1 = function () {
    return new Promise((result, failure) => {
        $.ajax("https://api.nulbox.com", {
            success: function (data) {
                result(data);
            },
            error: function (err) {
                failure(err);
            }
        });
    });
}
funcao2 = function () {
    funcao1()
        .then(d => console.log(d))
        .catch (e => console.error(e));
}
funcao2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
08.11.2018 / 20:05
1

The ajax function returns a jqXHR " that has a done method. That is, just return this object and use the method when you need the response of the request.

const request = function () {
  return $.ajax('https://jsonplaceholder.typicode.com/todos/1');
}

const response = request();

response.done(data => {
  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

FurtherReading:

  • What to use in Ajax, success or done?
08.11.2018 / 20:14