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

╄→尐↘猪︶ㄣ 提交于 2020-01-02 06:58:35

问题


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


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/41068126/how-can-i-abort-an-async-await-function-after-a-certain-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!