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

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

这可能是一个简单的问题和简单的答案,但我对这类事情不是很有经验。这是说 .then() 没有在此代码中定义。提前致谢。这是我的代码:

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);

当您 运行 代码片段时会看到错误。谁能告诉我如何解决这个问题?

您需要 return 您的 Promise,否则,您将返回 undefined(没有名为 then 的 property/function) .

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);