Structure of async callbacks in [removed] Synching

2019-08-30 00:17发布

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

2条回答
欢心
2楼-- · 2019-08-30 00:46

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?

查看更多
做个烂人
3楼-- · 2019-08-30 00:47

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

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

查看更多
登录 后发表回答