一段时间后如何中止async-await函数? [英] How can I abort an async-await function after a certain time?
本文介绍了一段时间后如何中止async-await函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,以下是一个异步函数:
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;
}
如果服务器滞后很多,我想中止此活动并返回错误.如何将超时设置为10秒(例如)?
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)?
推荐答案
您可以将哈希函数包装在另一个Promise中.
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);
这篇关于一段时间后如何中止async-await函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文