简体   繁体   中英

Javascript Async/Await - Cannot get it to work

My 1st post. I'm a Javascript 'hacker' (and feel much more comfortable with PHP, never gotten a hang of Javscript): I've tried for hours trying callbacks, delays, now ASYNC/AWAIT: Problem: AWAIT Code Not doing what I want. I've referenced multiple examples and forums, but not turn to stack overflow in desperate frustration!

Note: Expanding on this existing tool: https://github.com/webismymind/editablegrid/tree/master/examples (notice it says be sure to run AJAX in Synchronous)

DatabaseGrid.prototype.initializeGrid = function(grid) {

  var self = this;

    grid.setEnumProvider('id_Bolt', new EnumProvider({ 

        // the function getOptionValuesForEdit is called each time the cell is edited
        // here we do only client-side processing, but you could use Ajax here to talk with your server
        // if you do, then don't forget to use Ajax in synchronous mode 
        
        getOptionValuesForEdit: **async** function (grid, column, rowIndex) {
            
            var Thread_Code = grid.getValueAt(rowIndex, grid.getColumnIndex("Thread_Code"));
            
            **let** result = **new** setBoltEnum(Thread_Code);
            *console.log(Date.now() + " - 3 - " + **await** result.array);*
            return **await** result.array;

            
        *console.log(Date.now() + " - 4 - " + "ending function");*
        
        }
    }));
};

AJAX code it is calling:

setBoltEnum = function(Thread_Code){

        *console.log(Date.now() + " - 1 - calling AJAX");*
            result = $.ajax({
                url: 'EnumHelper.php',
                type: 'POST',
                dataType: "html",
                data: {
                    value: Thread_Code,
                    col_out: 'Descr',
                    col_search: 'Thread_Code',
                    tablename: 'Bolt_List'
                },
                success: function (response) {
                    result = JSON.parse(response);
                    *console.log(Date.now() + " - 2 - got AJAX response: " + result.resp);*
                    return result;
                    //_callback();
        
                },
                error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
                async: true
            });
};

Output in Chrome: 1 - calling AJAX 3 - undefined 2 - Got AJAX response - ok

(4) is not outputted

How can I get code to run 1-2-3-4?

You can only usefully await a promise.

You call setBoltEnum with new so it is treated as a constructor function and returns an object that is an instance of setBoltEnum (this doesn't make any sense because that function doesn't do anything that would be useful to use a constructor function for). It certainly doesn't return a promise.

setBoltEnum then calls $.ajax (which runs asynchronously) and assigns the result to result (You don't seem to have declared result so it is a global… this is probably bad, especially when dealing with asynchronous code). It then does nothing with that variable. It has no return statement at all so even if you didn't call it with new it will wouldn't return a promise.

Then you return await result.array; . There's no point in await ing as you return since you are going to be returning a promise anyway (because the function is async ). Here, result is the return value of $.ajax() which won't have an array property so the value is undefined (not a promise).

The next line is console.log but you never reach it because you just return ed.

Later the success function is called. This assigns a new value to result which might have an array property… but that also won't be a promise.


To fix this:

  • Don't use new when you aren't dealing with a constructor function
  • Don't use await when you aren't dealing with a promise or other thenable
  • Do return promises or other thenables from functions that work asynchronously
  • Don't mix callbacks ( success / error ) with promises (it just makes code hard to manage)
  • Do remember that $.ajax() returns a thenable (which you can await ).

Below code ended up working and outputted 1-2-3. Note, I stumbled upon this (adding ASYNC/AWAIT in setBoltEnum).

setBoltEnum = async function(Thread_Code){

        console.log(Date.now() + " - 1 - calling AJAX");
            return await $.ajax({
                url: 'EnumHelper.php',
                type: 'POST',
                dataType: "html",
                data: {
                    value: Thread_Code,
                    col_out: 'Descr',
                    col_search: 'Thread_Code',
                    tablename: 'Bolt_List'
                },
                success: function (response) {
                    result = JSON.parse(response);
                    console.log(Date.now() + " - 2 - got AJAX response: " + result);
        
                },
                error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
                async: true
            });
};


DatabaseGrid.prototype.initializeGrid = function(grid) {

  var self = this;

    grid.setEnumProvider('id_Bolt', new EnumProvider({ 

        // the function getOptionValuesForEdit is called each time the cell is edited
        // here we do only client-side processing, but you could use Ajax here to talk with your server
        // if you do, then don't forget to use Ajax in synchronous mode 
        
        getOptionValuesForEdit: async function (grid, column, rowIndex) {

            var Thread_Code = grid.getValueAt(rowIndex, grid.getColumnIndex("Thread_Code"));
            result = await setBoltEnum(Thread_Code);
            console.log(Date.now() + " - 3 - returning this: " + result);
            return result;
            //return expecting this  { "br" : "Brazil", "ca": "Canada", "us" : "USA" }; //result;

        
        }
    }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM