Receive result from an ajax as return

Asked

Viewed 82 times

0

Within the following scenario:

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

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

It is possible that I receive, even if it is through Premomises, the result of the funcao1 in funcao2?

  • See in the documentation what the function $.ajax returns.

3 answers

2

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

But you can also do it by creating a Promise ES6 style, 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>

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 example working here.

1

The function ajax has as return an object jqXHR which has a method done. That is, just return this object and use the method when you need the request reply.

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>

Further reading:

Browser other questions tagged

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