一旦调用 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);