【问题标题】:How do I get a reference to the current Promise within then()如何在 then() 中获取对当前 Promise 的引用
【发布时间】:2017-06-29 22:15:18
【问题描述】:

在下面的代码中,我想检查回调是从 latestRequest 执行的,所以我检查thisPromise 看它是否与latestRequest 相同。显然thisPromise 不起作用。有没有办法获得当前的承诺?

let latestRequest = MyLib
  .retrieve(getFilteredQuery(filters, queries, user))
  .then(res => {
    // Checking whether this is the latest request handler
    if (latestRequest === thisPromise) {
      updateData(res)
    }
  })
  .catch(err => {
    console.error(err)
  })

我的用例是处理来自 API 的请求。我只希望针对最新请求更新数据。请求可能需要不同的时间才能返回,有时较早的请求稍后会返回并覆盖最新的请求。如果您知道处理此问题的好方法,请告诉我。

【问题讨论】:

  • 我建议只为每个请求分配一个计数器(在请求范围内的某个位置)并跟踪您从中获得结果的最高计数器,然后您可以忽略任何较旧的请求(较低的计数器值)迟到的。这似乎也比试图比较承诺更防弹。请记住,一个 Promise 链由多个 Promise 组成,因为每次调用 new Promise() 或 .then() 都会创建一个新的 Promise。这不仅仅是一个链条中的一个承诺。您显示的代码中有多个活动的承诺。
  • 您的代码中只有一个latestPromise。请展示创建多个 Promise 的完整代码。
  • @Bergi 我已经包含了简化的示例代码。将该代码视为可以从应用程序中的其他位置调用的函数中的代码。
  • 好吧,那就只保留一个全局的latestPromise 和多个本地的thisPromise 变量。

标签: javascript promise cancellation


【解决方案1】:

在闭包内实现:

const run = (() => {
  let currentPromise;

  return () => {
    const p = new Promise((resolve, reject) => {
      // run an asynchronous process and resolve like resolve(results)
    })
    .then(results => {
      if (p === currentPromise) {
        // process results here
      }
    })

    currentPromise = p;
  }
})()

使用class的类似替代方案:

class Request {
  static #currentPromise;

  static run() {
    const p = new Promise((resolve, reject) => {
      // run an asynchronous process and resolve like resolve(results)
    })
    .then(results => {
      if (p === Request.#currentPromise) {
        // process results here
      }
    })

    Request.#currentPromise = p;
  }
}

您可以通过模拟延迟来进行测试:

const run = (() => {
  let currentPromise;

  return (timeout) => {
    const p = new Promise((resolve, reject) => {
      setTimeout(_ => resolve(timeout), timeout);
    })
    .then(data => {
      if (p === currentPromise) {
        console.log('latest request', data);
      }
    })

    currentPromise = p;
  }
})()

run(1000); // 1s request
run( 500);
run(  10); // last request, 0.1s

【讨论】:

  • 如果你只有静态属性,不要使用class语法
  • class 可以根据需要提供私有属性的封装。
  • 一个简单的 IIFE 或只是一个模块范围也可以做到这一点。无需滥用class 语法作为命名空间。
【解决方案2】:

没有任何方法可以从.then 提供的处理程序中调用promise 对象.then 的引用。

一个建议是为处理程序分配一个序列号,并从闭包中检查它是否是最后一个发出的。未经测试的例子:

let latestRequestId = 0;

let checkLatest = ()=> {
    let thisRequest = ++latestRequestId;
    return (res=>{
    // Checking whether this is the latest request handler
    if (latestRequestId === thisRequest) {
      updateData(res)
    }
  })
}

let latestRequest = MyLib
  .retrieve(getFilteredQuery(filters, queries, user))
  .then(checkLatest())
  .catch(err => {
    console.error(err)
  })

【讨论】:

  • 你有两个 latestRequest 变量在那里
  • 感谢@Bergi,已修复:)
猜你喜欢
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2014-01-14
  • 2019-03-07
  • 2023-03-05
相关资源
最近更新 更多