Kloud
Kloud

Reputation: 111

Why can I not call resolve() for Promises in SetTimeout Function directly

I have two versions of a sleep function, one is waiting for the resolve the other isn't:

function sleephelper1(ms) {
    return new Promise(function(resolve) {
        setTimeout(() => resolve('done'), ms);
    })
  }

  function sleephelper2(ms) {
    return new Promise(function(resolve) {
        setTimeout(resolve('done'), ms);           
    })
  }

Then I call either sleephelper1 or sleephelper2:

async function test(){
var test = await sleephelper1(3000);
console.log(test)
console.log("exit test function")
  }

test()

The first one is waiting 3 seconds before in resolves. But sleephelper2 ist not working properly. The code gets executed immediatly. I thought that SetTimeout can delay the call of a function by a given amount of time. Is resolve() not a function ? I have found this post JavaScript promise resolving with setTimeout which is quite what I am asking here, exept that I am using async await. Also I did not get the explanation. Could somebody explain to me why this behaves the way it does ?

Upvotes: 1

Views: 963

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84922

setTimeout(() => resolve('done'), ms);

This means "create a function with the text () => resolve('done') and pass it into setTimeout". setTimeout will wait the specified amount of time, and then call that function.

setTimeout(resolve('done'), ms);

This means "immediately call resolve('done') and pass its result into settimeout". the return value from resolve is undefined, so undefined is passed into setTimeout. There is thus no function for setTimeout to run 3 seconds later.

Upvotes: 5

Related Questions