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秒钟?
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;
}
你可以将哈希函数包装在另一个 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);
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;
async
关键字是否可以省略? - Markasync
关键字来包含await
调用,以便在运行时成为一个Promise。 - vsync