bugfix:解决异步请求和visible耦合问题及控制时序

51 阅读1分钟

原本代码结构:

function getItem() {
  GetItem(...params)
    .then((res) => {
      console.log(res);
      state.status = res.data.status
      state.visible = true;
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

getItem();

等待接口调用成功,再打开弹窗;后续发现,getItem的时候不一定每次都会打开弹窗,所以要解除getItem和visible的耦合,要解决异步请求和visible的耦合, 于是写成下面这种

function getItem() {
  GetItem(...params)
    .then((res) => {
      console.log(res);
      state.status = res.data.status
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

getItem();
state.visible = true

但此时就有问题,getItem是异步的,一定比visible晚,弹窗打开时,是没有数据的,单纯没有数据还好,一会就能渲染上去,但是我代码里面还有这么一段:

const statusMap = {
    statusA: {
        name: 'AAA',    
        operation: 'AA', 
        mode: 'A',
        color: 'warning',  
        nextStep: [{
            key: 'AAAA',
            content: 'AAAA'
        }]             
    },
    statusB: {
        name: 'BBB',
        operation: 'BB',
        mode: 'B',
        color: 'error',
        nextStep: [{
            key: 'BBBB',
            content: 'BBBB'
        }] 
    }
}

并且在渲染弹窗时,有这一段:

<a-tag :color="statusMap[status].color">
    {{ statusMap[status].name }}
</a-tag>

这可就完蛋了,因为初始是读不到status的值的,所以statusMap[status]也是undefined状态。因此,.color就会报错 image.png

最简单的解决办法

<a-tag :color="statusMap[status]?.color">
    {{ statusMap[status]?.name }}
</a-tag>

async / await解决办法

原本的代码结构是:

const A = () => {
    getItemA({ ...params })
        .then(res => {
            data = res.data;
        })
        .catch(console.log);
};

const B = () => {
    getItemB({ ...params })
        .then(res => {
            data = res.data;
        })
        .catch(console.log);
};

const C = () => {
    A();
    B();
};

C();

根据async和await的特性,await会解析后面的promise对象,等待promise对象的完成,因此,可以return promise对象的方式,进行时序控制。

const A = () => {
    return getItemA({ ...params })
        .then(res => {
            data = res.data;
        })
        .catch(console.log);
};

const B = () => {
    return getItemB({ ...params })
        .then(res => {
            data = res.data;
        })
        .catch(console.log);
};

const C = async () => {
    await A();
    await B();
};

C();