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?
promise.then(alert('after delay'));
Here you:
alert()
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:
promise.then(function(){
alert('after delay')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With