本文介绍了为什么我的承诺立即执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更全面地了解promises如何在JavaScript中运行并尝试下一个代码:
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'));
我想为JS setTimeout()函数编写一个包装器,我假设在10秒后出现警报执行此代码,但它立即显示,有人可以解释这里有什么问题吗?
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'));
在这里:
- 致电
alert()
- 将其返回值传递给
then()
- Call
alert()
- Pass its return value to
then()
因此承诺不会立即解决。它只是 alert
才能结算。
So the promise doesn't resolve immediately. You just alert
before it resolves.
你必须将函数传递给然后
。
promise.then(alert.bind(window, 'after delay'));
这篇关于为什么我的承诺立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!