0

I am trying to call the resolve after 10 seconds but I guess it is called directly.

let timer = (time) => new Promise((resolve)=> { setTimeout( resolve("success"),time)});

timer(10000).then( (result) => {
    alert(result)
})
JoshG
  • 6,472
  • 2
  • 38
  • 61

1 Answers1

-1

You're passing the return result of resolve() to setTimeout. You are not passing resolve() to setTimeout.

Remember basic programming in any programmig language (php, javascript, C, java etc.):

foo(bar())
// is the same as
temp = bar()
foo(temp)

So the correct way to pass resolve() to setTimeout is:

setTimeout(() => resolve("success"),time)
slebetman
  • 109,858
  • 19
  • 140
  • 171
  • Your code is not passing resolve to setTimeout. It's passing an anonymous function to setTimeout – gman Jul 17 '19 at 02:02
  • 1
    to pass resolve to setTimeout, you'd use something like `setTimeout(resolve, time, "success")` – Jaromanda X Jul 17 '19 at 02:19
  • Yes, after posting the question I figured out the issue, thanks. – Mohan Varma Jul 17 '19 at 02:30
  • @gman The correct way to pass a function that accepts an argument to setTimeout is to wrap it in an anonymous function. So the code **is** passing resolve to setTimeout (if you need to pass "success" to it) – slebetman Jul 17 '19 at 05:04
  • @gman I'm sure you already know it but: https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback/1190656#1190656 – slebetman Jul 17 '19 at 05:05
  • "Passing resolve to setTimeout" has a meaning. It means `setTimeout(resolve, ...)`. what you did is not that. You passed an anonymous function that calls resolve to setTimeout. That is not the same as "passing resolve to setTimeout". It's important to be precise when describing programming because not being precise leads to errors and misunderstandings. – gman Jul 17 '19 at 05:07
  • @gman That's correct. I'm passing an anonymous function that calls resolve because that's how you do it if you want to call resolve with an argument. It's answering an X/Y problem - X - how to pass resolve to setTimeout, answer Y - you don't, instead you wrap it in another function and pass that. The language is imprecise deliberately to better fit the question. The key here is nobody misunderstands what I mean by the words – slebetman Jul 17 '19 at 14:20
  • Actually most people new to JavaScript and or programming will completely mis-understand if you tell them this is how to pass function X to Y and you're not actually passing X to Y but you're passing something that calls X to Y. Again, it's programming. Be precise otherwise your just mis-informing people. Like "Q:how do I add a listener? A:you pass X to addListener. Q: And how do I remove the listener. A: You pass X to remove listener. Oh, and so `() => { x(); }` is how I "pass X to addListener and removeListener'. Fail! Words matter. – gman Jul 17 '19 at 14:30