简体   繁体   English

调用返回 setTimeOut 回调 javascript 的回调 function

[英]Calling a callback function that returns a setTimeOut callback javascript

I tried searching for this, but was unable to find something that matched the case I needed.我尝试搜索此内容,但无法找到与我需要的案例相匹配的内容。

I have this function here that can't be modified:我这里有这个不能修改的 function:

function generate() {
  const delay = 7000 + Math.random() * 7000;
  const num = Math.random();

  return (callback) => {
    setTimeout(() => {
      callback(num);
    }, delay);
  };
}

When I try to call the function like generate() I get an error.当我尝试像generate()一样调用 function 时出现错误。 I've also tried using a promise based approach like:我也尝试过使用基于 promise 的方法,例如:

    const result = await generate();
    return result;

But when I do that the result that is returned is a promise, which I can't render into JSX (I'm using React).但是当我这样做时,返回的结果是 promise,我无法将其渲染到 JSX(我正在使用 React)。

JSX component code (For debugging purposes currently): JSX 组件代码(目前用于调试目的):

const Test = () => { 
return <>{generate()}</>;
};

I would appreciate any suggestions here.我会很感激这里的任何建议。 Thanks!谢谢!

This in no way is to solve your problem, but only to understand this logic.这绝不是为了解决你的问题,而只是为了理解这个逻辑。 Maybe it can help in solving the problem.也许它可以帮助解决问题。

generate() in this case returns a function that sets the timeout.在这种情况下, generate() 返回一个设置超时的 function。

   typeof generate() = "function"
  // this is then the function we use to run the long running function

  const generateFunction = generate();

  //we then create the callback handler function
  const callback = () =>  {...}
  //when executed it will set the timeout to the random delay and display the result in your component of oyur choice.
  generateFunction(callback);

fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM