Search code examples
javascriptnode.jstypescriptpromise

Nodejs resolve promise if execution not completed withing given time


 return await new Promise(function (resolve, reject) {

 //some work goes here

resolve(true)

  });

With Settimeout

 return await new Promise(function (resolve, reject) {

 //some work goes here

setTimeout(function() { resolve(true); }, 5000);

  });

With setTimeout it is waiting for 5 sec even though my task completed in 1 sec. my requirement is if task complete within 5 sec then promise should resolve immediately else it will resolve at 5 sec


Solution

  • Clear the timeout when your task completes normally :

    return new Promise(function (resolve, reject) {
    
        let safetyTimeout = setTimeout(resolve, 5000);
    
        //some work goes here
    
        // When it's done :
    
        clearTimeout(safetyTimeout);
        resolve();
    });