Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I abort an async-await function after a certain time?

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)?

like image 680
ABC Avatar asked Dec 09 '16 20:12

ABC


1 Answers

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;
like image 197
Patrick McElhaney Avatar answered Nov 11 '22 10:11

Patrick McElhaney