Search code examples
javascriptjqueryajaxes6-promise

Cannot read then of undefined on promises


I'm trying to get a response from a function, to execute another function, but I don't receive the response. I get the following error on: "TypeError: Cannot read property 'then' of undefined." I followed this tutorial, I tried to use Promises but no success. Here's my code

function i_emp() {
    const form = $("#msform");
    const formdata = getFormData(form); // Return a data inputs JSON
    const table_emp = formdata.table_emp;
    const json_emp = {
        // DATA HERE
    };
    $.ajax({
        url: "./class/Class_Insert.php",
        type: "POST",
        dataType: "json",
        data: {
            table_name: table_emp,
            data: json_emp,
        },
        success: function(result) {
            console.log(result);
        },
        error: function() {
            console.log({
                error: "Error"
            });
        }
    }).then(() => {
        return json_emp;
    });

    function env() {

        i_emp().then(function(result) {
            console.log(result);
        });

        // const resultado = i_emp();  // I tryed this one but no success
        // console.log(resultado); 

    }

Solution

  • function i_emp() {
      return new Promise(function(resolve, reject){
        const form = $("#msform");
        const formdata = getFormData(form); // Return a data inputs JSON
        const table_emp = formdata.table_emp;
        const json_emp = {
            // DATA HERE
        };
        $.ajax({
            url: "./class/Class_Insert.php",
            type: "POST",
            dataType: "json",
            data: {
                table_name: table_emp,
                data: json_emp,
            },
            success: function(result) {
                resolve(result);
            },
            error: function() {
                reject({
                    error: "Error"
                });
            }
        });
     });
    }
    
    function env(){
     i_emp().then(function(result) {
      console.log(result);
     }, function(error){
      console.log(error);
     });
    }