[英]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:我想更彻底地了解 promises 在 JavaScript 中的工作原理,我尝试了以下代码:
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.我想为 JavaScript
setTimeout()
function 编写一个包装器,我假设alert
应在 10 秒后执行。 However, this code shows it immediately.但是,此代码会立即显示它。
Could someone explain what is wrong here?有人可以解释这里出了什么问题吗?
promise.then(alert('after delay'));
Here you:你在这里:
alert()
alert()
then()
then()
So the promise doesn't resolve immediately.所以承诺不会立即解决。 You just
alert
before it resolves.你只是在它解决之前发出
alert
。
You have to pass a function to then
.您必须将函数传递给
then
。
promise.then(alert.bind(window, 'after delay'));
Add function
to your then
statement:在
then
语句中添加function
:
promise.then(function(){
alert('after delay')
});
The reason is explain by Quentin's answer .原因由昆汀的回答解释。 An additional solution would be using arrow functions:
另一个解决方案是使用箭头函数:
promise.then(() => alert('after delay'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.