0

I'm trying to get a kind of getter methos using promises , it's working but I get the promise on the return instead of the data , I'm not sure about what is wrong on the code

function _get_username(){
    var user_promise = new Promise( (resolve, reject) => {
        $.ajax({
            url:'/get_username',
        }).done(function(data, textStatus, jqXhr){
            console.log(data);
           resolve(data);
        }).fail( function(err){
            reject(err);
        });
    });
}

async function get_username(){
    try{
        var username = await _get_username();
    }catch(err){
        Swal.fire({
            icon: 'error',
            text: err.message,
          })
    }
    
    return username;
}


console.log(get_username());
af_159623
  • 197
  • 10
  • async functions return a Promise - that's what they are designed to do – Bravo Nov 23 '20 at 20:21
  • oh, and `_get_username` won't return anything useful, in fact your code won't even wait for that ajax to start let alone finish – Bravo Nov 23 '20 at 20:21
  • `_get_username` has no `return` statement, so it returns `undefined` and not the promise you assign to `user_promise` – Quentin Nov 23 '20 at 20:21
  • You're using the nested promise anti-pattern. `$.ajax()` returns a thennable object, you can just use that instead of wrapping it in *another* promise. – Quentin Nov 23 '20 at 20:22

0 Answers0