Why my promise executes immediately

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?

Answers:

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

Add function to your then statement:

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

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.