简体   繁体   中英

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. 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.

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. Do not block my question just to grow up your EXP on 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,.

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.

So, in another words just write after the asyncFunc invoke the .then tail in like next way 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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