簡體   English   中英

如何在Javascript中將多個函數編譯成函數鏈?

[英]How to compile multiple functions into function chain in Javascript?

我希望能夠將一個函數(對於我正在處理的 Web 框架)編譯為大多數 Web 框架中所見的“函數鏈”。 什么是最簡單的方法來做到這一點? 假設我有一個函數列表:

const middleware = [
function(data, next){
    console.log(data); 
    next()
},
function(data, next) {
   return;
}, function(data, next) { }];

在上述情況下,理想的行為是第一個函數被觸發,傳入的參數next觸發下一個函數,然后由於return語句而結束鏈。 我怎么能把它編譯成一個函數?

不是 100%,但我相信如果你在第一個函數之后為完成的產品創建一個變量,你可以將第二個函數應用於它並將它從第一個函數傳遞給第二個函數

您可以簡單地減少函數數組:

functionList.reduce((output, fn) => fn(output), undefined);

這將按順序運行它們,將上一次調用的結果作為參數傳遞給下一次調用,最終以上次函數調用的最終結果結束。

舉個例子,如果你用這個作為你的函數列表:

[
  () => 4,
  n => n+5,
  n => `$${n}`,
  amt => amt + '.00'
]

結果將是$9.00

好的,我找到了答案 - 您可以使用以下代碼,該代碼是我改編自 koa-compose.yml 的。 要編譯中間件鏈,您可以使用以下函數:

function compiler(middleware) {
  // return function to execute compiled middleware chain
  return function(data, next) {
    // set pointer to 0 to match middleware index to track if next()
    // is called twice in one middleware
    let pointer = 0;
    function dispatch(i) {
      // check if pointer is larger than i, indicating next() was called more than once
      if (i < pointer)
        return Promise.reject(
          new Error("next() called multiple times in one middleware function.")
        );
      // set pointer to next index
      pointer = i + 1;
      // grab current function
      let fn = middleware[i];
      // if out of middleware, assign the next function from the parameters to be executed next
      if (i === middleware.length) fn = next;
      // if no function (out of middleware and no provided parameter), end middleware execution
      if (!fn) return Promise.resolve();
      try {
        // run next function, binding the second parameter to the next middleware in the chain
        return Promise.resolve(fn(data, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err);
      }
    }
    // start function on first middleware
    return dispatch(0);
  };
};

您可以編譯中間件函數並按如下方式執行它:

const funcs = [
     function(data, next){
          console.log(data); next();
     }, function(data, next){
        console.log('done');
     }];
const compiled = compiler(funcs);

// execute compiled middleware chain
compiled();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM