Structure of async callbacks in javascript: Synching the Asynch

I find the seperation of code between when using callbacks makes my code harder to understand and maintain.

How do you handle the problem?

Here are a couple of solutions I have come up with, using, as an exaple, asynch web service calls. Please let me know what you think, and and pros or cons that occur to you.

via closures:

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);
    });
}

via recursion:

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);
    }
}

With newer versions of jquery every thing is changing regarding callbacks.

http://addyosmani.com/blog/jquery-1-7s-callbacks-feature-demystified/


Async callbacks are something you will just have to deal with in web programming. I think its just a case of getting into the mindset that something will be called eventually.

I don't tend to see code in real life like your 2nd example so I'd be wary of this approach. You first approach is more like the way to go but it looks a little old school to me.

As I seem to be in the habbit of giving you links rather than answering your question as fully as I like. I'll refer you to deffered objects. I personally find them at least initally even less readible but when you get them you wont be able to understand how you did without.

What are deferred objects?

链接地址: http://www.djcxy.com/p/55308.html

上一篇: 为什么我的phpsessid是2个Ajax请求之间的变化

下一篇: 在javascript中异步回调的结构:同步异步