首页 > 解决方案 > 每次点击触发不同的 API 调用

问题描述

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

问题是,当我单击需要大约 6000 年才能加载的项目#1 以及在需要 2000 年才能加载的项目#2 之后,我将显示最后点击的项目 - 这是项目#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 对象的模拟。

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

标签: javascriptjquerypromisees6-promise

解决方案


创建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)
            }
        });
    }
});

推荐阅读