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){

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?


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

Add function to your then statement:

    alert('after delay')

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

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.