簡體   English   中英

使用回調組織Javascript

[英]Organizing Javascript with callbacks

我正在嘗試找出在網站上組織一堆AJAX方法的最佳方法。 問題是我想在收到每個回調之后運行一堆回調。 這是一個示例(假設每個方法都異步運行):

Log_in_user
    if response received and call was successful
        get_user's_data
            if response received and call was successful
                alert user

希望現在問題已經解決。 因為每種方法都是異步運行的,所以代碼不會按順序運行。 如果相反,我想傳遞下一個函數作為要在執行該函數的函數之后運行的回調,則我將不得不將越來越多的回調傳遞給第一個函數,具體取決於每個函數之后要發生的事情異步方法返回。 例如,在這種情況下,我將必須將兩個回調傳遞給Log_in_user函數Log_in_user(get_user's_data,alert_user)。 我彼此之間運行的回調越多,傳遞給原始Log_in_user函數的回調也就越多。

有沒有更模塊化和更好組織的方式來做到這一點?

jQuery 1.5為您做到這一點,您可以使用.when()

例:

function doAjax(){
    return $.get('/echo/html/');
}

function doMoreAjax(){
    return $.get('/echo/html/');
}

$.when( doAjax(), doMoreAjax() )
    .then(function(){
        console.log( 'I fire once BOTH ajax requests have completed!' );
    })
    .fail(function(){
        console.log( 'I fire if one or more requests failed.' );
    });

來自jsfiddle

為什么不在服務器上生成此文件? 在客戶端只需打一個電話

LoginUserAndGetData

返回

{hasErrors: false, userLoggedIn: true, userName : "User", data : {}}

{hasErrors: true, errorMessage: "SomeText", errorCode : "Something you can work with"}

我一直在像這樣向我的函數添加回調...

function doThis( cb ) {
  // do stuff here
  if ( typeof cb === 'function' ) cb();
}

function thenThis() {
  // callback functionality
}

doThis( thenThis );

編輯:

抱歉,我真的應該已經通讀了您需要做的更多工作...

什么時候處理純ajax調用是一個很好的選擇,但是,如果需要在回調中進行額外的功能,我發現了另一個可以幫助我組織代碼的模式...

// Log_in_user
//     if response received and call was successful
//         get_user's_data
//             if response received and call was successful
//                 alert user

var ajax = {
        logIn : function( cb ) {
            $.ajax({
                // params
            }).success( parseCB ).error( this.errorCB );
            function parseCB( doc ) {
                // logic
                if ( typeof cb === 'function' ) cb();
            }
        },
        userData : function( cb ) {
            $.ajax({
                // params
            }).success( parseCB ).error( this.errorCB );
            function parseCB( doc ) {
                // logic
                if ( typeof cb === 'function' ) cb();
            }
        },
        errorCB : function(){
            // logic
        }
    },
    my = {
        init : function() {
            ajax.logIn( this.done.logIn );
            if ( typeof cb === 'function' ) cb();
        },
        done : {
            logIn : function() {
                ajax.userData( this.done.userData );
            },
            userData : function() {
                // Do stuff with user data, then run my.done.page (the final callback)
                alert( 'user data recieved' );
            },
            page : function() {
                // set up clicks, or whatever else you need
                alert( 'everything is done' );
            }
        }
    };

$( function() {
    my.init( my.done.page );
});

這看起來可能有點多,但是我對這種模式的想法是使我的所有回調和實際函數調用都在文檔中以及在my變量中保持就緒。 jQuery是我選擇的框架,因此我將它放在那里……我對此很開放,謝謝。

暫無
暫無

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

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