简体   繁体   中英

Javascript promises error says that .then() is not defined. Asynchronous

This is probably a simple question with a simple answer, but I am not very experienced with this sort of stuff. It is saying that .then() is not defined in this code. Thanks in advance. Here is my code:

 const Mypromise = num => { new Promise( function(resolve, reject) { if (num === 0) { resolve('Zero was inputted') } else { reject('You put in a number other than zero') }}) } // const num = () => Math.floor(Math.random() *2) const handleSuccess = handleResolve => {console.log(handleResolve)}; const handleFailure = handleReject => {console.log(handleReject);} Mypromise(5 ).then(handleSuccess).catch(handleFailure);

The error will be seen when you run the code snippet. Could someone tell me how to fix this?

You need to return your Promise , otherwise, you're returning undefined (which doesn't have a property/function called then ).

 const Mypromise = num => { // return the Promise return new Promise(function(resolve, reject) { if (num === 0) { resolve('Zero was inputted') } else { reject('You put in a number other than zero') } }) } // const num = () => Math.floor(Math.random() *2) const handleSuccess = handleResolve => { console.log(handleResolve) }; const handleFailure = handleReject => { console.log(handleReject); } Mypromise(5).then(handleSuccess).catch(handleFailure);

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