简体   繁体   中英

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 .

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.

Thank You.

The EventListener is present only the Error/Success function won't be called again. I added an console.info - Statement to show that the EventListener are being called.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM