簡體   English   中英

Javascript 異步/等待 - 無法讓它工作

[英]Javascript Async/Await - Cannot get it to work

我的第一篇文章。 我是 Javascript 的“黑客”(並且對 PHP 感覺更舒服,從未掌握過 Javscript):我已經嘗試了幾個小時嘗試回調、延遲,現在是 ASYNC/AWAIT:問題:等待代碼沒有做我想要的. 我參考了多個示例和論壇,但沒有絕望地轉向堆棧溢出!

注意:擴展此現有工具: https://github.com/webismymind/editablegrid/tree/master/examples (注意它說一定要同步運行 AJAX)

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 代碼:

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 在 Chrome 中:1 - 調用 AJAX 3 - 未定義 2 - 得到 AJAX 響應 - 好的

(4) 不輸出

如何讓代碼運行 1-2-3-4?

您只能await 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) . 它當然不會返回 promise。

setBoltEnum然后調用$.ajax (異步運行)並將結果分配給result (您似乎沒有聲明result ,所以它是全局的……這可能很糟糕,尤其是在處理異步代碼時)。 然后它對那個變量什么都不做。 它根本沒有返回語句,所以即使你沒有用new調用它,它也不會返回 promise。

然后你return await result.array; . 在您returnawait沒有意義,因為無論如何您都將返回 promise (因為 function 是async )。 在這里, result$.ajax()的返回值,它沒有array屬性,因此該值是undefined的(不是承諾)。

下一行是console.log ,但你永遠不會到達它,因為你只是return ed。

后來success function 被調用。 這會為可能具有數組屬性的result分配一個新值……但這也不會是 promise。


要解決這個問題:

  • 不處理構造函數 function 時不要使用new
  • 當您不處理 promise 或其他 thenable 時,請勿使用await
  • 從異步工作的函數中返回 Promise 或其他 thenables
  • 不要將回調( success / error )與承諾混合(這只會使代碼難以管理)
  • 請記住$.ajax()返回一個 thenable (您可以await )。

下面的代碼最終工作並輸出了 1-2-3。 請注意,我偶然發現了這一點(在 setBoltEnum 中添加 ASYNC/AWAIT)。

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;

        
        }
    }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM