javascript - 执行一段时间后返回函数

标签 javascript node.js return settimeout

完全清楚,如果重要的话,我会在 Node 中执行此操作。

我有一个方法可以进行一些同步调用(它们依赖于下一个调用的反馈,因此必须是同步的),并且我对环境或我正在调用的事物没有太多控制权。

无论这些调用是否已完成,我都需要在设定时间(大约 3 秒)后返回一个值。如果这些调用已完成,则脚本完成并返回值。一种备份超时,它返回可接受的(如果不完整)值,而不是由于服务器执行限制而完全超时并引发错误。

我立即想到使用setTimeout()(如果没有被触发,则使用clearTimeout())来执行返回。但是,显然,在 setTimeout 回调中返回一个值并不会结束我的脚本并返回该值 - 那么我该怎么办?

//"myFunction" being consumed by something I don't have control over
//Otherwise I'd just wrap the caller in a timeout
myFunction = async () => {

    var scripttimer = setTimeout(function(){
        //emergency exit - script took longer than 3 seconds
        return "I need to return a value for myFunction now"; 
    }, 3000);

    //multiple synchronous remote https calls are made
    //right here which could sometimes cause this function
    //to take more than 3 seconds, at which point the 
    //scripttimer should kill myFunction by making it return 
    //a value. That's the part that I'm asking how to do, if 
    //even possible

    if (scripttimer){
        //if we took less than 3 seconds, we don't need the backup 
        //callback in scripttimer and so we're going to kill it
        clearTimeout(scripttimer);
    }

    //best scenario return value, script took less than 3 seconds
    return "did this anyways";
}

尝试过

考虑进行 try-catch- throw 设置:

try {

    var scripttimer = setTimeout(function(){
        throw "I need to return a value for myFunction now"; 
    }, 3000);

    //wait 4 seconds maybe
    if (scripttimer){
        clearTimeout(scripttimer);
    }
    return "I don't make it out if I take too long";


} catch (e){
    return "acceptable enough";
}

...但是 catch 没有捕获它,这有点有意义,因为抛出的错误超出了 try-catch 的范围,因为它是异步的...所以这是迄今为止我最好的想法。

最佳答案

如果将 httpCall 函数中的延迟更改为小于 3 秒,那么您将获得输出 hello

如果 httpCall 中的延迟超过 3 秒,那么您将得到的输出为 bye

// Your Http Call Here which may take 3 seconds or more. eg.5 seconds


function httpCall(){
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
        resolve("hello")
    },5000)
  });
}

// your main function where you will be calling sync functions
function operation(){
  return new Promise((resolve,reject)=>{
    const timeoutID = setTimeout(function(){
        resolve("bye")
    },3000)
    httpCall().then(result=>{
       clearTimeout(timeoutID)
       resolve(result)
    })
  });
}

// This is how you should call
operation().then((result)=>console.log(result))

Check execution here

关于javascript - 执行一段时间后返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029972/

相关文章:

javascript - 如何将 React Context 中的值传递给 Redux-Saga 函数?

node.js - Node ssh2 到 ssh 并以用户身份 sudo su 并运行命令

c++ - 返回单检查条件

javascript - 如何在 Angular 6 中循环链接 Promise

ajax 请求返回后,Javascript 对象属性变为未定义

javascript - 如何将 HTML 表单导出为二维码?

ruby - 在 ruby​​ 的字符串中使用方法返回

javascript - 在 swagger 文档中实现 void

javascript - React/Redux 状态在第二次操作调用时为空

c - 使用 c 函数返回多个变量