'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?



Solution 1:[1]

Add function to your then statement:

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

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matej Marconak
Solution 2 t.niese