简体   繁体   中英

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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