如何在变量内部调用函数?

时间:2018-07-16 14:13:22

标签: javascript node.js

这可能是一个基本问题,但我被困在这里。

const activate = (server, plugin) => {
  let handlers = {
    async beginBlock(request) {
      //...my functon code here
    }
  }
};

我想知道如何从外部库调用beginBlock()函数吗? 到目前为止,我尝试了activate.handlers.beginBlock(request),但没有成功。

2 个答案:

答案 0 :(得分:0)

尝试

const activate = (server, plugin) => {
    const beginBlock = async (request) => {
        //...my functon code here
    }
    return beginBlock;
};

const beginBlock = activate(server, plugin);
beginBlock(request);

答案 1 :(得分:0)

我想用稍微更新的代码扩展Rahul Sharma的响应,这将使您可以从库外部调用多个功能。

const activate = (server, plugin) => {
    const beginBlock = async (request) => {
        //...my functon code here
    }
    const endBlock = async (request) => {
        //... my function code here
    }
    return {
        beginBlock: beginBlock,
        endBlock: endBlock
    };
};

const beginBlock = activate(server, plugin);
beginBlock(request);

const endBlock = activate(server, plugin);
endBlock(request);