Promise 函数编程

一旦调用 then 立刻返回一个 promise,他的状态由 then 里面的回调 返回值决定,

1、不返回  成功的peomise 值 undefined

2、 一个值  成功的peomise 下个then 的成功回调的参数 就是该值

3、一个promise , 调用then返回 的promise 状态由该 promise 决定


<!-- 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);

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值