V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cout2013mr
V2EX  ›  程序员

贴段代码,求优化意见

  •  
  •   cout2013mr ·
    Marstin · 2018-04-12 16:42:34 +08:00 · 1378 次点击
    这是一个创建于 2204 天前的主题,其中的信息可能已经有所发展或是发生改变。
    define(["Message"],function (Message) {
    	//事件流代码链式执行工具
        function PromiseUtil(func) {
            obj = {
            	flag:true,
            	catchError:true,
            	//执行当前需要执行的代码块
            	excute:function(flag,func){
            		try {
            			func.call();
            			//前面执行步骤没问题则继续执行下一步
            			this.flag = flag;
            		} catch (err){
            			this.catchError = false;
            			if(Message.check(err.utflag) && err.isAlert()){
            				alertmsg(err.message,err.type,err.tips);
            			} else {
            				console.error(err);
            			}
            		}
                },
                //定义下一步需要执行的方法块
                then:function(func){
                	if(this.catchError === false)
                		return;
                	if(this.flag == null || this.flag == true)
                		func.call();
                	this.func = func;
                },
                //执行下一步需要执行的方法块
                work:function(){
                    this.func.call();
                }
            };
            return obj;
        }
        return PromiseUtil;
    });
    

    主要功能是实现代码块的流程式执行,现在生成代码是以下这种嵌套模式:

    ${code_1}.then({
    	${code_2}.then({
    		${code_3}.then({
    			······
    		})
    	})
    });
    

    要怎么样改造成下面这种链式的代码执行模式呢?

    ${code_1}.then({
    	${code_1}
    }).then({
    	${code_2}
    }).then({
    	······
    });
    

    如果还有其他优化意见,也请提供,蟹蟹。

    2 条回复    2018-04-12 17:53:46 +08:00
    zjsxwc
        1
    zjsxwc  
       2018-04-12 16:50:40 +08:00
    jquery 的 defferred 了解下 http://api.jquery.com/jquery.deferred/
    cout2013mr
        2
    cout2013mr  
    OP
       2018-04-12 17:53:46 +08:00
    @zjsxwc 谢谢= =我看下是怎么实现的,我这里场景其实有点不太一样,比如说我这个代码块中,可能是一个弹出的确认窗口,然后要点击确定之后,才能算是执行成功;以及一些类似的方法块,都是等待用户操作完成的,这个好像就没办法支持的
    比如下面这个代码就会在第一次确认之后,直接打印 2,4,而不是先打印 2,等待确认之后,载打印 4
    var dtd=$.Deferred();
    $.when(confirm(dtd)).done(function(){console.log(2)}).done(confirm(dtd)).done(function(){console.log(4)})
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5355 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 07:49 · PVG 15:49 · LAX 00:49 · JFK 03:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.