最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

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

Share Improve this question asked Dec 9, 2016 at 20:12 ABCABC 1,4773 gold badges19 silver badges29 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

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;
发布评论

评论列表(0)

  1. 暂无评论