承诺问题:ReferenceError:拒绝未定义

Ann*_*ein 3 javascript

我正在使用一些自己构建的承诺示例来了解此功能的工作原理。

以下代码产生错误

参考错误:拒绝未定义

我从节点 Promise.js 开始,并使用节点版本 8.11.3

这是我的代码,产生错误的部分用“问题

function testPromise () {

//part 1
  function checkCountOnServer () {
    return new Promise(function (resolve, reject) {
      var available = false
      if (available) {
        resolve('available')
      }
      else {
        reject('not available')
      }
    })
  }

  function checkPayment () {
    return new Promise(function (resolve, reject) {
      var booleanTest = true
      if (booleanTest) {
        resolve('payment done')
      }
      else {
        reject('no payment received')
      }
    })
  }

  var checkCountOnServerVar = checkCountOnServer()
  checkCountOnServerVar.then(function (resolve) {
    console.log(resolve)
    return resolve(checkPayment())
  }, function (reason) {
    console.log(reason) //works
    reject(reason) // problem
  }).then(function (value) { console.log(value) },
    function (rejected) {
      console.log(rejected) //problem
    })

}

testPromise()
Run Code Online (Sandbox Code Playgroud)

我实际上希望消息“不可用”两次。

即使我将 reject(reason) 更改为 reject('test') 我也会得到同样的错误。

请帮帮我。

Jon*_*lms 5

 checkCountOnServerVar.then(function (resolve) {
Run Code Online (Sandbox Code Playgroud)

使用then承诺解析为的任何值调用回调,这"payment done"在您的情况下,这不是函数,因此您不能调用它。要从 then 处理程序中链接一个 promise,只需返回它:

checkCountOnServerVar.then(function (status) {
 console.log(status);
 return checkPayment();
})
Run Code Online (Sandbox Code Playgroud)

此外,您的错误捕获器根本没有意义,

function (reason) {
  console.log(reason) //works
  reject(reason) // problem
}
Run Code Online (Sandbox Code Playgroud)

由于reject未定义,并且您实际上没有处理错误。如果您不处理错误,则附加处理程序没有意义,否则您应该return使用链可以继续的值,例如:

function(error) {
  console.error("Something bad happened", error);
  return "An error occured, but we don't mind...";
}
Run Code Online (Sandbox Code Playgroud)

总结:

checkCountOnServer()
  .then(serverCount => checkPayment())
  .then(payment => console.log(payment))
  .catch(error => console.error(error));
Run Code Online (Sandbox Code Playgroud)