ABC*_*ABC 3 javascript async-await
例如,以下是一个异步函数:
async function encryptPwd() {
const salt = await bcrypt.genSalt(5);
const encryptedPwd = await bcrypt.hash(password, salt);
return encryptedPwd;
}
Run Code Online (Sandbox Code Playgroud)
如果服务器滞后很多,我想中止此活动并返回错误。如何将超时设置为10秒(例如)?
您可以将哈希函数包装在另一个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);
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用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;
Run Code Online (Sandbox Code Playgroud)