【问题标题】:Is it possible to pass in function with parameter that does not exist yet?是否可以使用尚不存在的参数传入函数?
【发布时间】:2018-12-21 12:56:45
【问题描述】:

如果标题没有意义,真的很抱歉。不知道如何让我的问题简短

我想知道的是,

我有一个recursive function,好吧不一定是recursive function,只是我在做这个功能的时候,我想知道它是否可以以更灵活的方式重用。

我的函数看起来像这样runAxios(ele, api)是我想知道是否可以重复使用的函数

const ct = (arr, num, res) => {
  const promises = [];

  for(let i = 0; i < num; i++){
    const ele = arr.shift();  // take out 1st array, literally take out
    if(ele){
      promises.push(
        runAxios(ele, api)  // this is the function I am wondering if can be reused
      )
    }
  }

  Promise.all.......
};

如果runAxios(ele, api) 可以是任何东西,那么我相信这个ct 可以更灵活?

我想知道它是否可以像这样

const ct = (arr, num, res, fx) => {
  const promises = [];

  for loop......
    if(ele){
      promises.push(
         fx  // this is then passed as any other function other than just a fixed `axios function` that I wrote
      )
    }
  }

Promise.all........

};

当我第一次尝试时,我意识到这是行不通的,因为runAxios 的第一个参数是在循环内完成的,这意味着该变量在进入函数本身之前还不存在。

只是好奇是否有这样一种方法可以轻松做到,我只是不知道如何或实际上不可能?

提前感谢您的任何建议。

【问题讨论】:

    标签: javascript function parameters parameter-passing


    【解决方案1】:

    当然可以。您只需调用使用所需参数传递的函数。您将计算 ele 参数,然后将其传递给函数。下面显示了一个查看其工作方式的通用示例:

    const functionToBeCalled = (parameter1, parameter2) => {
      console.log(parameter1 + parameter2);
    }
    
    const ct = (fx) => {
      //..code
        let ele = 1;
        fx(ele, 2);
      //..code
    };
    
    ct(functionToBeCalled);

    【讨论】:

      【解决方案2】:

      您的方法非常接近。它应该看起来像这样:

      const someFunction = (x) => new Promise((resolve) => resolve(x));
      
      const ct = (arr, fn) => {
        const promises = arr.filter(x => x).map(x => fn(x));
        
        Promise.all(promises).then(x => console.log(x));
      };
      
      ct([1, 2, 3], someFunction);

      (我还冒昧地用更紧凑的方法替换了您的循环。)

      【讨论】:

        猜你喜欢
        • 2018-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 2013-03-17
        相关资源
        最近更新 更多