async使用出现的神奇bug

113 阅读1分钟

事情是这样的,在调用接口判断时,用了async去执行,导致添加接口完了,查询列表接口获取不到数据,经过确认发现是查询时,还没添加上数据导致的。换了promise写法就能正常获取到了,不过上面的现象也是偶发事件,不清楚原因,写了下demo也能正常获取到执行结果,疑惑中。。。

demo示例

function promise1() {
    const p1 = new Promise(resolve => {
        setTimeout(() => {
            resolve('promise1');
            console.log('promise1');
        }, 200)
    });
    return p1;
}

function promise2() {
    const p2 = new Promise(resolve => {
        setTimeout(() => {
            resolve('promise2');
            console.log('promise2');
        }, 200)
    });
    return p2;
}

function call() {
    console.log('func');
}

async function func() {
    const flag = false;
    await (flag ? promise1() : promise2());
    call()
}

func();

// 运行结果
// promise2
// func

出现现象的代码

this.$refs.formRef.validate(async valid => {
    if (!valid) return;
    // 接口
    const form = {
        ...this.form,
        productId: this.$route.params.id,
    };
    (await form.id)
        ? product.updateMs(this.resource, form.id, form)
        : product.addMs(this.resource, form);
        
    this.$message.success('保存成功');
    this.handleClose();
    this.$emit('refresh');
});

说明:

上面这段代码中通过async获取接口数据,然后再执行下面的refresh事件刷新,这么写理论上是先调取接口,再执行刷新事件,这样就能正常刷新到数据了,但是结果是偶尔刷新不到数据。

修改后的代码

this.$refs.formRef.validate(valid => {
    if (!valid) return;
    // 接口
    const form = {
        ...this.form,
        productId: this.$route.params.id,
    };
    const apiFun = form.id
        ? product.updateMs(this.resource, form.id, form)
        : product.addMs(this.resource, form);
    apiFun.then(() => {
        this.$message.success('保存成功');
        this.handleClose();
        this.$emit('refresh');
    });
});

说明:

通过promise的then执行时,来执行refresh事件,这样能完全保证了能刷新到数据的更新或者添加,不会出现上面的偶发问题。

问题点

第一种写法为啥会出现这种问题?有知道的在评论区讨论吧。