【问题标题】:Each click triggers different API call每次点击触发不同的 API 调用
【发布时间】:2018-11-30 09:14:13
【问题描述】:

我有列表,每个点击的项目都会触发不同的 API 请求。每个请求都有不同的持续时间。成功后,我将显示一些数据。

问题是,当我点击 item#1 大约需要 6000 来加载,然后在 item#2 需要 2000 加载之后,我将显示最后点击的项目 - 这是 item#2,因为它有已经加载,一旦 item#1 收到数据,我的数据将更改为该数据。这是错误的,因为我想显示最新点击的数据。

这就是我处理事件的方式:

 newList.on('click', 'li', (e) => {
                let id = $(e.currentTarget).data("id");
                store.getCharacterDetails(id).then(docs => {
                    this.clearDetails();
                    this.charDetails = docs;
                    this.displayDetails(this.charDetails);
                })

我的 API 是来自 store 对象的模拟。

我想这可以按预期工作,但我确实希望最后一个触发的请求有效。

【问题讨论】:

  • 那么从逻辑上讲,当另一个请求应该开始时,您会想要取消之前未完成的所有请求。
  • 如果您需要更详细的建议,您需要向我们提供有关getCharacterDetails 工作原理的更多信息。但是,关于取消正在运行的 Promise 的一般问题,请参阅 stackoverflow.com/q/30233302/215552

标签: javascript jquery promise es6-promise


【解决方案1】:

一个粗略而简单的方法可以是创建一个数组并推送 ID,在异步操作之后您可以检查它是否是最新的点击。但陷阱是,如果cleardisplayDetails 需要很长时间,并且如果有人在清除和显示时单击,它将不会记录最新的单击。

不管怎样,这里是代码,也许你可以用它做出更好的东西。

var latestClick = [];
newList.on('click', 'li', (e) => {
    let id = $(e.currentTarget).data("id");
    latestClick.push(id);
    store.getCharacterDetails(id).then(docs => {
        if(id === latestClick[latestClick.length - 1]){
            this.clearDetails();
            this.charDetails = docs;
            this.displayDetails(this.charDetails);
            latestClick = [];
        }
    })
})

【讨论】:

    【解决方案2】:

    使charDetails 成为一个对象,该对象保留所有结果,并以 id 为键。跟踪最后点击的 id。

    // in constructor
    this.charDetails = {};
    this.lastId = null;
    
    newList.on('click', 'li', (e) => {
        let id = $(e.currentTarget).data("id");
        this.lastId = id;
        if (this.charDetails[id] === id) {  // don't cancel requests, cache them!
            this.displayDetails(this.charDetails[id])
        } else {
            store.getCharacterDetails(id).then(docs => {
                // this runs later, cache the result
                this.charDetails[id] = docs;
                if (id === lastId) {  // only update UI if the id was last clicked
                    this.displayDetails(docs)
                }
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 2016-08-27
      相关资源
      最近更新 更多