1

I try to execute specific code when the request is over.

However I don't know if it's the good way to do it.

Can you tell and help me for this please?

Thanks!

Ajax request

function envoyerRequete(url, data, type) {
    return $.ajax({
        url: url,
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        type: type
    }).done(function (data) {
        console.log('sucess');
        return true;
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log('fail');
        return false;
    });
}

Ajax call

function newAuteur() {
    var data = {
        "nom": $("#nomAuteur").val(),
        "prenom": $("#prenomAuteur").val()
    };
    var result = envoyerRequete('/auteurs/', data, "POST");
    if(result) {
        // blabla true
    }
    else {
        // blabla false
    }
}
Royce
  • 1,557
  • 5
  • 19
  • 44

1 Answers1

2

Simply you can use Async/await

async function newAuteur() {
    var data = {
        "nom": $("#nomAuteur").val(),
        "prenom": $("#prenomAuteur").val()
    };
    var result = await envoyerRequete('/auteurs/', data, "POST");
    if(result) {
        // blabla true
    }
    else {
        // blabla false
    }
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Is there anything special to do to import `await` and `async`? Because my IDE doesn't know. – Royce Mar 09 '19 at 16:03
  • 1
    @N.Lamblin you read on the links attached to answer. and you need not to import anything. it's an es6 feature inbuilt in JS – Code Maniac Mar 09 '19 at 16:06
  • My bad stupid mistake. However when I use Async/await like you I got this error in Chrome console : `Uncaught (in promise)`. Any idea? – Royce Mar 09 '19 at 17:15