简体   繁体   English

为什么 promise 的 `then()` 处理程序会立即执行?

[英]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:你在这里:

  1. Call alert()调用alert()
  2. Pass its return value to 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.

相关问题 为什么将 redux 调用包装到承诺中允许“立即”访问结果 - Why does wrapping a redux call into a promise allows the access of the result "immediately" 为什么Promise在诺言完成之前执行'then'子句? - Why does the Promise execute the 'then' clause before promise has completed? 为什么jQuery立即执行传递给.click()的函数? - Why does jQuery immediately execute functions passed to .click()? 为什么JavaScript Promise然后处理程序在其他代码之后运行? - Why does JavaScript Promise then handler run after other code? 为什么我的函数在我的 Promise 回调之前执行? - Why does my function execute before my promise callback? 为什么 Firebase 云 Function 执行定义的 Promise - Why does Firebase Cloud Function execute defined Promise 为什么我的ES6 Promise Rejection需要立即使用以避免出现控制台错误消息? - Why does my ES6 Promise Rejection need to be consumed immediately to avoid a console error message? 为什么Promise.all(数组)没有立即解决? - Why the Promise.all(array) not resolved immediately? 为什么promise 用promise 解决? - Why does promise resolve with promise? 如何立即执行猫鼬查询并通过Promise.all等待它们? - How to execute mongoose queries immediately and wait for them with Promise.all?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM