2011-11-21 131 views
0

我發現使用回調之間的代碼分離使得我的代碼難以理解和維護。javascript中的異步回調的結構:同步異步

你是如何處理這個問題的?

下面是我提出的幾個解決方案,使用它作爲一個例外的異步Web服務調用。請讓我知道你的想法,以及發生在你身上的優點或缺點。

通過關閉:

sayHelloWithClosures: function() 
{ 
    //Do something first 
    // The following call's signature is: ServiceName(SuccessCallback, FailureCallback);   
    TestBasicWebServices.SL.WebService1.HelloWorld(
    function (result) 
    { 
     //Do something next 
     alert(result); 
    }, 
    function (error) 
    { 
     //Do Exception 
     alert(error._message); 
    }); 
} 
通過遞歸

sayHello: function (result) 
{ 
    if (result == undefined) 
    { 
     //Do something first 
     // The following call's signature is: ServiceName(SuccessCallback, FailureCallback); 
     TestBasicWebServices.SL.WebService1.HelloWorld(this.sayHello, this.sayHello); 
    } 
    else if (typeof (result) == "string") 
    { 
     //Do something next 
     alert(result); 
    } 
    else 
    { 
     //Do Exception 
     alert(result._message); 
    } 
} 

回答

1

異步回調的東西,你將不得不應對網絡編程。我認爲它只是一個進入思維的案例,最終會被調用。

我不喜歡在你的第二個例子中看到現實生活中的代碼,所以我會對這種方法保持警惕。你的第一個方法更像是要走的路,但它對我來說看起來有點古老。

因爲我似乎處於爲您提供鏈接而不是像我喜歡的那樣完全回答您的問題的習慣。我會把你推薦給對象。我個人發現他們至少在初始階段更不可讀,但是當你得到他們時,你將無法理解你沒有。

What are deferred objects?