javascript中异步回调的结构:同步Asynch [英] Structure of async callbacks in javascript: Synching the Asynch

查看:35
本文介绍了javascript中异步回调的结构:同步Asynch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现使用回调之间的代码分隔使我的代码更难以理解和维护.

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

您如何处理该问题?

以下是我提出的一些解决方案,例如使用异步Web服务调用.请让我知道您的想法,以及您的利弊.

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.

通过闭包:

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

推荐答案

异步回调是您在Web编程中必须处理的事情.我认为这只是进入最终将被称为某种东西的思维方式的一种情况.

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.

什么是递延对象?

这篇关于javascript中异步回调的结构:同步Asynch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆