美文网首页
Javascript简单实现middleware

Javascript简单实现middleware

作者: 梁王io | 来源:发表于2017-09-19 09:49 被阅读30次

    前言

    自己遇到的一个面试题,感觉挺有趣的。

    实现效果(需求)

    完成fun函数

    function fun1(ctx, next) {
      ctx.index++;
      next();
    }
    function fun2(ctx, next) {
      setTimeout(function() {
        ctx.index++;
        next();
      }, 1000);
    }
    function fun3(ctx, next) {
      ctx.index++;
    }
    
    function fun() {
    }
    var obj = {index:0}
    fun([fun1,fun2,fun3], obj) //按fun1,fun2,fun3的顺序,遇到next到下一个函数。最后对象的index应该是3 
    

    实现代码

    function fun1(ctx, next) {
      ctx.index++;
      console.log(1);
      next();
    }
    function fun2(ctx, next) {
      setTimeout(function() {
        ctx.index++;
        console.log(2);
        next();
      }, 1000);
    }
    function fun3(ctx, next) {
      ctx.index++;
      console.log(3);
    }
    
    function fun(funarr, ctx) {
      let funIndex =0;
      function next() {
        funIndex++;
        funarr[funIndex] && funarr[funIndex].call(null, ctx, next);
      }
      funarr[0](ctx, next);
    }
    var obj = {index:0}
    

    后记

    后面有时间研究一下express中间件的实现解析。

    相关文章

      网友评论

          本文标题:Javascript简单实现middleware

          本文链接:https://www.haomeiwen.com/subject/kftwsxtx.html