-1

Hey guys I have a js promise question but it is giving me errors

function delay(n) {
    return new Promise((resolve) => setTimeout(resolve, n*1000));
}

This is supposed to say it is now 2 seconds later and then is is now 1.5 seconds later but it says

It is now undefined later
It is now undefined later

delay(2)
    .then(seconds => console.log(`It is now ${seconds} later`))
    .then(() => delay(1.5))
    .then(seconds => console.log(`It is now ${seconds} later`));
deceze
  • 510,633
  • 85
  • 743
  • 889

2 Answers2

0

You are not including a resolve value; change setTimeout(resolve to setTimeout(function() {resolve(n);}.

WBT
  • 2,249
  • 3
  • 28
  • 40
  • The core issue is that OP's code is not including a resolve value. – WBT Mar 22 '21 at 15:39
  • Protip: `setTimeout(resolve, n * 1000, n)`… – deceze Mar 22 '21 at 15:40
  • My issue is that this is not waiting that amount of seconds to print. Like with the first .thenm it should wait 2 seconds to print that message and then 1.5 for the next one and Idk where to add that delay because doing *1000 inside the resolve or after doesnt work – Christian Nodal Mar 22 '21 at 15:47
  • 1
    @Christian `return new Promise(res => setTimeout(res, n * 1000, n))`. This. This works. If it doesn't, you'll need to show your actual code. The code in your question should already be delaying correctly, you're simply not passing the value of `n` through. This answer fixes that. – deceze Mar 22 '21 at 15:50
-1

setTimeout accepts multiple parameters;

setTimeout(function, milliseconds, param1, param2, ...)

So after you've set the second setTimeout paramter to the milliseconds you want to wait, you can pass any additional parameters;

So change

setTimeout(resolve, n*1000)

To

setTimeout(resolve, n*1000, n)

function delay(n) {
    return new Promise((resolve) => setTimeout(resolve, n*1000, n));
}
delay(2)
    .then(seconds => console.log(`It is now ${seconds} seconds later`))
    .then(() => delay(5))
    .then(seconds => console.log(`It is now ${seconds} seconds later`));
0stone0
  • 34,288
  • 4
  • 39
  • 64