How can I abort an async-await function after a certain time?
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;