简体   繁体   English

基于Promise的异步setTimeout吗? 诺言 { <pending> }错误

[英]Async setTimeout on Promise based? Promise {<pending>} Error

So, I'm trying to bring my function work with async timers logic, where I need to execute computeResult (func for example) after the timer is stop. 因此,我试图使函数与异步计时器逻辑一起工作,在计时器停止后,我需要在该逻辑上执行computeResult (例如,func)。 To get the setTimeout async logic under control I had used the Promise based asyncFunc function, but it always return me Promise {<pending>} when I used it. 为了控制setTimeout异步逻辑,我使用了基于Promise的asyncFunc函数,但是使用它时,它总是返回Promise {<pending>}

Where is my fall in this case? 在这种情况下我跌倒在哪里? Thank you. 谢谢。

PS I also see the various posts on this topic on SoF, but it does not help me. 附言:我还在SoF上看到了有关此主题的各种帖子,但这对我没有帮助。 Do not block my question just to grow up your EXP on SoF 不要只是为了增加您在SoF上的经验而阻止我的问题

const computeResult = () => {
  return 'sdas'
}

const asyncFunc = () => new Promise(
   r => setTimeout(r, 1000))
     .then(() => computeResult()
);

export default asyncFunc

Not 100% sure what your trying to do,. 不100%不确定您要做什么。

But the following might be what your after. 但是以下可能是您的追求。

 const computeResult = () => { return 'sdas' } const asyncFunc = () => new Promise(resolve => setTimeout(() => resolve(computeResult()), 1000) ); console.log("Wait for computeResult"); asyncFunc().then(r => console.log(r)); 

You write all right in this case, except one little think. 在这种情况下,您会写得很好,但请三思而后行。 You forgot to execute the Promise after it has been resolved, that's why it stuck on <pending> state. 您在解决Promise后忘记执行该Promise ,这就是为什么它停留在<pending>状态。

So, in another words just write after the asyncFunc invoke the .then tail in like next way asyncFunc().then(your_sersult => ddoSomething(your_sersult)) 因此,在另一个词语只写后asyncFunc调用.then尾巴在像下方式asyncFunc().then(your_sersult => ddoSomething(your_sersult))

That's all. 就这样。 You will get what you want :) 你会得到你想要的:)

You can read more about it on the MDN site: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 您可以在MDN网站上阅读有关它的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM