[英]Why my event listener won't last after one event when using Promise in ES6?
I have following code (a simple one): 我有以下代码(一个简单的代码):
Code: 码:
var myPromise = new Promise(function(success, error) { document.getElementById("success").addEventListener("click", function() { success({ msg: "This is success", code: 100 }); }); document.getElementById("error").addEventListener("click", function() { error({ msg: "This is error", code: 10 }); }); }); console.log("Hello"); myPromise.then(function(content) { console.log(content.msg); }); myPromise.catch(function(content) { console.log(content.code); });
<button id="success">Success</button> <button id="error">Error</button>
Clicking on either two buttons for first time will either log This is success
or 10
. 首次单击两个按钮之一将记录“
This is success
或“ 10
。
Why clicking on either two button for second, third, and subsequent times will not log anything in console window? 为什么第二次,第三次及以后两次单击两个按钮都不会在控制台窗口中记录任何内容 ? why the event listener seems to be suddenly gone?
为什么事件监听器似乎突然消失了?
FYI: I'm currently experimenting with Promise in ES6 to understand how it works. 仅供参考:我目前正在ES6中尝试Promise,以了解其工作原理。
Thank You. 谢谢。
The EventListener is present only the Error/Success function won't be called again. 仅提供了Error / Success函数,不会再调用EventListener。 I added an
console.info
- Statement to show that the EventListener are being called. 我添加了
console.info
语句以显示正在调用EventListener。
var myPromise = new Promise(function(success, error) { document.getElementById("success").addEventListener("click", function() { console.info("called success" ); success({ msg: "This is success", code: 100 }); }); document.getElementById("error").addEventListener("click", function() { console.info("called error" ); error({ msg: "This is error", code: 10 }); }); }); console.log("Hello"); myPromise.then(function(content) { console.log(content.msg); }); myPromise.catch(function(content) { console.log(content.code); });
<button id="success">Success</button> <button id="error">Error</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.