8

For example, the following is an async function:

async function encryptPwd() {
  const salt = await bcrypt.genSalt(5);
  const encryptedPwd = await bcrypt.hash(password, salt);
  return encryptedPwd;
}

If the server is lagging a lot, I want to abort this activity and return an error. How can I set a timeout for like 10 sec (for example)?

ABC
  • 1,387
  • 3
  • 17
  • 28

2 Answers2

10

You could wrap the hash function in another promise.

function hashWithTimeout(password, salt, timeout) {
    return new Promise(function(resolve, reject) {
        bcrypt.hash(password, salt).then(resolve, reject);
        setTimeout(reject, timeout);
    });
}


const encryptedPwd = await hashWithTimeout(password, salt, 10 * 1000);
TOPKAT
  • 6,667
  • 2
  • 44
  • 72
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167
  • 2
    Could the `async` keyword be dropped from the outer function, since it's returning a promise on its own? – Mark Dec 12 '17 at 16:34
  • @Mark - while it does return a promise, keep it mind that it only actually returns a promise after all the code before it had ran & done, so therefor. this is why the `async` keyword much be used in the function hold the `await` calls, so it will be a promise at run-time. – vsync Oct 09 '18 at 19:14
7

Another option is to use Promise.race().

function wait(ms) {
  return new Promise(function(resolve, reject) { 
    setTimeout(resolve, ms, 'HASH_TIMED_OUT');
  });
}

 const encryptedPwd = await Promise.race(() => bcrypt.hash(password, salt), wait(10 * 1000));

 if (encryptedPwd === 'HASH_TIMED_OUT') {
    // handle the error
 }
 return encryptedPwd;
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167