【发布时间】:2020-11-13 06:46:34
【问题描述】:
这是我的代码:
let delayTimeout = null;
const delayExecution = mls => {
console.log('Delaying for', mls);
return new Promise(resolve => {
delayTimeout = setTimeout(() => resolve('ok'), mls);
})
}
const main = async () => {
axios.post('URL', {data})
.then(response => {
if(response passes some condition){
clearTimeout(delayTimeout);
}
})
const res = await delayExecution(30000)
console.log("DONE!")
}
main();
在 axios 调用之后,我可能想通过清除其中的超时来终止 delayExecution。如何在我的 delayExecution 函数中清除超时但仍解决 Promise?
本质上,我试图在它的时间之前完成delayExecution,但仍然解决其中的承诺。
【问题讨论】:
-
我真的不明白你在做什么。如果您不想清除超时 - 因为您希望函数在 10 秒后仍然执行 - 那么就不要调用
clearTimeout。 -
取决于
/* Seome logic here */我可能希望函数在 10 秒之前执行。 -
所以你想有条件地改变超时的持续时间?那为什么不根据你需要的任何逻辑设置一个变量,比如
duration,然后在最后做setTimeout(doneFunc, duration)? (但我可能仍然不了解您的要求。) -
不是我想有条件地改变超时的持续时间,而是在某些情况下,我希望
setTimeout函数早点完成,这种情况下我仍然想要doneFunc函数运行。 -
您的 setTimeOut 函数精确地用于在延迟后执行您的
doneFunc函数。如果您希望它在之前运行,请不要使用 setTimeOut
标签: javascript