简体   繁体   English

Javascript 承诺错误表示 .then() 未定义。 异步

[英]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.据说 .then() 没有在这段代码中定义。 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 ).您需要return您的Promise ,否则,您将返回undefined (它没有名为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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