ABC ABC -4 years ago 163
Javascript Question

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

Answer Source

You could wrap the hash function in another promise.

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

const encryptedPwd = await hashWithTimeout(password, salt, 10 * 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download