Why my promise executes immediately

2020-02-02 03:37发布

问题:

I want to learn more thoroughly how promises work in JavaScript and trying the next 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 JS setTimeout() function and I assume alert appearing after 10 sec while executing this code but it shows immediately, could someone explain what is wrong here?

回答1:

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'));


回答2:

Add function to your then statement:

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


回答3:

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

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