【问题标题】:Cancelation token created with promise使用承诺创建的取消令牌
【发布时间】:2018-08-29 02:39:39
【问题描述】:

我有一个功能,我想使用它并理解它

对我来说最难的部分是 token.promise 和取消功能。有人可以描述下面的函数是如何工作的吗?

export function createCancelToken () {
  const token = {}
  let cancel
  token.promise = new Promise(resolve => {
    // The cancelation function
    cancel = reason => {
      // The reason can be checked synchronously to see if the promise is canceled
      token.reason = reason
      resolve(reason)
    }
  })

  return [token, cancel]
}

【问题讨论】:

  • 你在哪里找到这个不是你自己写的代码?
  • 如果要在语义上准确,我觉得cancellationToken 应该是reject() 而不是resolve() ......不过只是一个挑剔。

标签: javascript promise es6-promise cancellation


【解决方案1】:

token 是一个包含token.promise 的对象,并且可能在未来的某个时间点上包含token.reason

token.promise 是一个实际的承诺,具有 .then.catch 方法。显然.then 将在promise 被取消后被调用,reason 作为唯一的参数。

因此,您调用函数let arr = createCancelToken() 并从中获取令牌并取消对象let token = arr[0]; let cancel = arr[1]。稍后您可以调用cancel('no reason');token.promise.then(reason => {}) 将在该处运行,reason 表示“没有理由”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2015-01-23
    • 2017-10-09
    • 2018-12-10
    相关资源
    最近更新 更多