我有这个try-catch代码块:
async function matchMaking(userId) {
try {
const user = await User.findOne({
_id: userId
});
var timeOut1 = setTimeout(function() {
return {
success: false,
msg: "matchMaking aleready done"
};
}, 20000);
//some code
if (match === true) {
clearTimeout(timeOut1);
return {
success: true
};
}
} catch (e) {
return {
success: false,
error: e
};
}
}我的用法如下:
matchMaking(userId).then(res => {
if (res.success) {
console.log("success")
} else {
console.log("failed")
}
});当( match === true )正常时,我在控制台中得到“成功”,但当( match === false)时,我希望在20秒后在控制台中看到“失败”。但是return在setTimeout中不起作用,我什么也得不到。
发布于 2018-08-01 21:15:14
您需要从matchMaking函数返回一个Promise。
async function matchMaking (userId) {
return new Promise((res, rej) => {
const user = await User.findOne({
_id: userId
});
var timeOut1 = setTimeout(function() {
return res({
success: false,
msg: "matchMaking aleready done"
});
}, 20000);
if (match === true) {
clearTimeout(timeOut1);
return res({
success: true
});
}
});
}这样,当您像这样调用它时-它将按照预期运行:
matchMaking(userId).then(res => {
if (res.success) {
console.log("success")
} else {
console.log("failed")
}
});更好的处理方法是使用promise的reject回调:
async function matchMaking (userId) {
return new Promise((res, rej) => {
const user = await User.findOne({
_id: userId
});
var timeOut1 = setTimeout(function() {
return rej({
success: false,
msg: "matchMaking aleready done"
});
}, 20000);
if (match === true) {
clearTimeout(timeOut1);
return res({
success: true
});
}
});
}这样,当您像这样调用它时-您可以使用.catch()来处理失败状态:
matchMaking(userId)
.then(res => console.log("success"))
.catch(err => console.log("failed"));https://stackoverflow.com/questions/51632636
复制相似问题