简体   繁体   English

如果需要超过一定时间,节点 js 暂停执行语句

[英]Node js to suspend execution of statement if takes longer than certain time

I want to suspend execution of a statement if it takes more than certain time.如果需要超过一定时间,我想暂停执行语句。 Help me please to achieve this?请帮助我实现这一目标?

In the below given sample snippet of code, if the statement const result = await curly.get('www.google.com');在下面给出的示例代码片段中,如果语句const result = await curly.get('www.google.com'); takes more than 2 seconds of time to complete execution I want to suspend execution of the statement and throw an exception.完成执行需要超过 2 秒的时间我想暂停执行语句并抛出异常。

 const { curly } = require('node-libcurl'); exports.curlFetch = async () => { try { const result = await curly.get('www.google.com'); return result; } catch (err) { console.error('----------ERRORR OCCURRED----------', err); throw err; } }

You can use Promise.race()您可以使用Promise.race()

I have defined an timeout function that returns an promise that rejects after an certain amount of time.我已经定义了一个timeout function ,它返回一个 promise 在一定时间后拒绝。 If the request is faster then the 3 seconds the result will be resolved otherwise the timeout rejects and you land into the catch block如果请求更快,则结果将在 3 秒内得到解决,否则超时将被拒绝,您将进入catch

 const { curly } = require('node-libcurl'); exports.curlFetch = async () => { try { const request = curly.get('www.google.com'); const result = await Promise.race([request, timeout(3000)]) return result; } catch (err) { console.error('----------ERRORR OCCURRED----------', err); throw err; } } function timeout(ms) { return new Promise((res, rej) => setTimeout(rej("Request took too long"), ms)); }

from msdn来自 msdn

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. Promise.race()方法返回一个 promise,一旦可迭代中的一个承诺履行或拒绝,就会履行或拒绝,其值或原因来自该 promise。

const fetchWithTimeout =  (url, options, timeout = 2000) => {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}


await fetchWithTimeout('www.google.com',{})

further reading:进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

As the others have suggested, Promise.race() will continue script execution after a timeout, but it will not stop the execution of your curly function.正如其他人所建议的那样, Promise.race()将在超时后继续执行脚本,但它不会停止执行您的curly function。 Verify this with:验证这一点:

const wait = (t)=>new Promise((r,j)=> {
  setTimeout(()=>r(t),t*1000)
}); 
Promise.race([ 
  wait(1).then(console.log),
  wait(5).then(console.log)
])

Supposing curly has an abort function on the request you can do:假设 curl 有一个 abort curly您可以执行的请求:

const TIMEOUT_SEC = 20;
const wait = (t)=>new Promise((r,j)=> {
  setTimeout(()=>r(t),t*1000);
});
let req = curlyWhatever();
let handled = false;
await Promise.race([
  req.then(()=>handled=true),
  wait(TIMEOUT_SEC).then(()=>{
    if(handled)
      return;
    req.abort();
    // do whatever else
  })
])

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

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