Promise 函数编程

发布时间:2024年01月06日

<!-- App.vue -->
<template>
<!-- The following is the modal box component -->
   <div class="modal" v-show="visible">
     <div>
       User name: <input v-model="info.name" />
     </div>
     <!-- Other information -->
     <button @click="handleCancel">Cancel</button>
     <button @click="handleConfirm">Submit</button>
   </div>
   <!-- Page components -->
</template>
<script setup>
import { provide } from 'vue';
const visible = ref(false);
const info = reactive({
   name: ''
});
let resolveFn, rejectFn;
// Pass the information collection function to the following
provide('getInfoByModal', () => {
   visible.value = true;
   return new Promise((resolve, reject) => {
     // Assign the two functions to the outside and break through the promise scope
     resolveFn = resolve;
     rejectFn = reject;
   });
})
const handleConfirm = () => {
   resolveFn && resolveFn(info);
};
const handleCancel = () => {
   rejectFn && rejectFn(new Error('User has canceled'));
};
</script>

接下来,getInfoByModal就可以通过直接调用模态框来轻松获取用户填写的数据。?

<template>
   <button @click="handleClick">Fill in the information</button>
</template>

<script setup>
import { inject } from 'vue';
const getInfoByModal = inject('getInfoByModal');
const handleClick = async () => {
   // After the call, the modal box will be displayed. After the user clicks to confirm, the promise will be changed to the fullfilled state to obtain the user information.
   const info = await getInfoByModal();
   await api.submitInfo(info);
}
</script>

let resolveFn;
let rejectFn;

function getComLogic() {
  /** isShowBoing:true  */
  let p: {[k: string]: any} = new Promise((resolve, reject) => {
    resolveFn = resolve;
    rejectFn = reject;
  });

  p._data = {
    d1: 'data1',
    d2: 'data2',
  };
  return p;
}

(async () => {
  let p = await getComLogic();
  console.log(p);
})();

/**
 * click event
 */
setTimeout(() => {
  /**
   * 用户操作,eg: 点击弹窗,输入信息
   */
  resolveFn(getComLogic()._data);
}, 1000);

文章来源:https://blog.csdn.net/gu2022_3_5_21_23/article/details/135426139
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。