简体   繁体   English

如何为NodeJs中的方法设置时间限制?

[英]How to set a time limit to a method in NodeJs?

I have a use case, where I am doing an external API call from my code,我有一个用例,我正在通过我的代码进行外部 API 调用,
The response of the external API is required by my code further on我的代码进一步需要外部 API 的响应

I am bumping into a scenario, where the external API call at times takes far too long to return a response,我遇到了一个场景,外部 API 调用有时需要太长时间才能返回响应,
casing my code to break, being a serverless function将我的代码设置为无服务器 function

So I want to set a time limit to the external API call,所以我想给外部API调用设置一个时间限制,
Where if I don't get any response from it within 3 secs, I wish the code to gracefully stop the further process如果我在 3 秒内没有得到任何响应,我希望代码能够优雅地停止进一步的过程

Following is a pseudo-code of what I am trying to do, but couldn't figure out the logic -以下是我正在尝试做的伪代码,但无法弄清楚逻辑 -

let test = async () => {
    let externalCallResponse = '';

    await setTimeout(function(){ 

        //this call sometimes takes for ever to respond, but I want to limit just 3secs to it
        externalCallResponse = await externalCall();
    }, 3000);

    if(externalCallResponse != ''){
        return true;
    }
    else{
        return false;
    }
}

test();

Reference -参考 -
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParameters-property https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParameters-property
I'm using AWS SSM's getParameters method我正在使用 AWS SSM 的 getParameters 方法

You cannot await setTimeout as it doesn't returns a Promise .您不能等待setTimeout ,因为它不会返回Promise

You could implement a function that returns a Promise which is fulfilled after 3 seconds.您可以实现一个 function,它返回Promise ,它会在 3 秒后完成。

function timeout(seconds) {
   return new Promise((resolve) => {
       setTimeout(resolve, seconds * 1000)
   });
}

You can await the above function in your code passing the number of seconds you want to wait for您可以在代码中等待上面的 function 传递您要等待的秒数

let test = async () => {
    let externalCallResponse = ''; 
    
    setTimeout(async () => {
       externalCallResponse = await externalCall();
    }, 0);

    await timeout(3); // wait for 3 seconds 

    if(externalCallResponse != '') return true;
    else return false;
}

Following code snippet demonstrates the usage of timeout function written above.以下代码片段演示了上面编写的timeout function 的用法。 It mocks a api request that returns a response after 4 seconds.它模拟 api 请求,该请求在 4 秒后返回响应。

 function timeout(seconds) { return new Promise(resolve => { setTimeout(resolve, seconds * 1000); }); } function apiRequest() { return new Promise(resolve => { setTimeout(() => resolve('Hello World'), 4000); }); } let test = async () => { let externalCallResponse = ''; setTimeout(async () => { externalCallResponse = await apiRequest(); }, 0); await timeout(3); // wait for 3 seconds if (externalCallResponse;= '') return true; else return false; }. test().then(res => console.log(res)).catch(err => console.log(err;message));

You could do something like this:你可以这样做:

const timeout = async (func, millis) => {
   return new Promise(async (resolve, reject) => {
      setTimeout(() => reject(), millis);

      resolve(await func());
   });
}

timeout(() => doStuff(), 3000)
   .then(() => console.log('worked'))
   .catch(() => console.log('timed out'));

Tests:测试:

 const timeout = async (func, millis) => { return new Promise(async (resolve, reject) => { setTimeout(() => reject(), millis); resolve(await func()); }); } const doStuffShort = async () => { // Runs for 1 second return new Promise((resolve) => setTimeout(() => resolve(), 1000)); } const doStuffLong = async () => { // Runs for 5 seconds return new Promise((resolve) => setTimeout(() => resolve(), 5000)); } timeout(() => doStuffShort(), 3000).then(() => console.log('1 worked')).catch(() => console.log('1 timed out')); timeout(() => doStuffLong(), 3000).then(() => console.log('2 worked')).catch(() => console.log('2 timed out'));

you can use something like this, I created a function that return a promise then I used this promise.你可以使用这样的东西,我创建了一个返回 promise 的 function,然后我使用了这个 promise。

let test = async () => {

    return promiseTimeout()
}

const promiseTimeout = () => {
    return new Promise(async (resolve, reject) => {
        setTimeout(function () {
            let externalCallResponse=""
            externalCallResponse = await externalCall();
            if (externalCallResponse != '') {
                return resolve(true);
            }
            else {
                return resolve(false);
            }
        }, 3000);
    })
}

test().then(result=>{
    console.log(result);
});

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

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