Promise.resoleve() 实际应用场景

139 阅读1分钟

现有如下业务场景:

image.png

  • 姓名必填,电话非必填
  • 电话号码输入完成,失焦后需后端检验
  • 点击提交,如有输入电话号码,需等待电话号码校验完成后,提交表单

解救方案一

const loading = ref<undefined | Promise<boolean>>();
/**
 * 电话号码失焦事件
 */
const onBlurValidate = () => {
  loading.value = postValidate()
    .then(() => {
      return true;
    })
    .finally(() => (loading.value = undefined));
};
/**
 * 提交按钮点击事件
 */
const handleSubmit = () => {
  if (loading.value) {
    loading.value.then(() => {
      //todo 提交表单
      loading.value = undefined;
    });
  } else {
    //todo 提交表单
  }
};

解救方案二 Promise.resoleve()优化代码


const loading = ref<Promise<void>>(Promise.resolve());
/**
 * 电话号码失焦事件
 */
const onBlurValidate = () => {
  loading.value = postValidate().finally(() => (loading.value = Promise.resolve()));
};
/**
 * 提交按钮点击事件
 */
const handleSubmit = () => {
  loading.value.then(() => {
    //todo 提交表单
    loading.value = Promise.resolve();
  });
};