SimonD
SimonD

Reputation: 1547

Why does the `then()` handler of a promise execute immediately?

I want to learn more thoroughly how promises work in JavaScript and I tried the following code:

function delay(timeout) {
    return new Promise(function(resolve, reject){
        setTimeout(resolve,timeout);
    });
}

var promise = delay(10000);
promise.then(alert('after delay'));

I wanted to write a wrapper for the JavaScript setTimeout() function and I assume alert should execute after 10 seconds. However, this code shows it immediately.

Could someone explain what is wrong here?

Upvotes: 4

Views: 1221

Answers (3)

t.niese
t.niese

Reputation: 40842

The reason is explain by Quentin's answer. An additional solution would be using arrow functions:

promise.then(() => alert('after delay'));

Upvotes: 2

Quentin
Quentin

Reputation: 943214

promise.then(alert('after delay'));

Here you:

  1. Call alert()
  2. Pass its return value to then()

So the promise doesn't resolve immediately. You just alert before it resolves.

You have to pass a function to then.

promise.then(alert.bind(window, 'after delay'));

Upvotes: 9

Matej Marconak
Matej Marconak

Reputation: 1413

Add function to your then statement:

promise.then(function(){
    alert('after delay')
});

Upvotes: 5

Related Questions