前言
从实战问题中剖析知识点
1. 问题所示
执行Vue3数据的时候,终端输出的data如下所示
Promise {<pending>}
[[Prototype]] : Promise
[[PromiseState]] : "fulfilled"
[[PromiseResult]] : Array(13)
截图如下所示:
2. 知识分析
输出的数据是JavaScript的Promise对象的
对于这个数据基本的数据分析如下:
Promise {<pending>}
:Promise对象的初始状态,处于等待状态[[Prototype]]: Promise
:对象的原型链,通过Promise构造函数创建的[[PromiseState]]: "fulfilled"
:Promise对象的内部状态,已经成功完成[[PromiseResult]]: Array(13)
:对象的结果
对于Promise的状态有如下:
- Pending(待定):Promise刚创建时的初始状态
- Fulfilled(成功):操作成功完成,Promise有了结果
- Rejected(失败):操作失败,Promise有了失败的原因
Promise的结果:当Promise状态变为fulfilled时,会有一个对应的结果值,这里是一个包含13个元素的数组
正确处理Promise的结果,例如使用.then()
和.catch()
方法
比如查看输出内容:
myPromise.then(result => console.log(result));
做适当的错误处理:
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.error('Error:', error);
});
给个示例Demo:
function fetchData() {
return new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
const data = Array(13).fill('example data');
resolve(data);
}, 1000);
});
}
// 使用Promise
fetchData()
.then(result => {
console.log('Promise fulfilled with result:', result);
})
.catch(error => {
console.error('Promise rejected with error:', error);
});
3. 实战
通过实战理解更加透彻
const handleAdd = () => {
if (props.formType === 'detail') return // 禁用“添加危险品”按钮
const row = {
id: undefined,
shipName: undefined,
voyage: undefined,
billNumber: undefined,
boxNumber: undefined,
boxSize: undefined,
boxType: undefined,
productName: undefined,
hazardousLevel: undefined,
hazardCode: undefined,
isOpentopOrHigh: undefined,
appointmentId: undefined,
}
row.appointmentId = props.appointmentId
const data = AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId)
console.log(data)
// 确保 data 是数组并赋值给 formData.value.list
const fetchedData = Array.isArray(data) ? data : [];
formData.value.list = [...formData.value.list, ...fetchedData];
formData.value.list.push(row) // 添加新条目到列表中
console.log('Updated list:', formData.value.list);
}
其中data输出问题所示的内容,那么处理此类问题有如下两种方式
- 使用Promise的
.then()
方法来处理异步API调用的结果
const handleAdd = () => {
if (props.formType === 'detail') return // 禁用按钮
const row = {
id: undefined,
shipName: undefined,
voyage: undefined,
billNumber: undefined,
boxNumber: undefined,
boxSize: undefined,
boxType: undefined,
productName: undefined,
hazardousLevel: undefined,
hazardCode: undefined,
isOpentopOrHigh: undefined,
appointmentId: undefined,
}
row.appointmentId = props.appointmentId
// 调用API并处理结果
AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId)
.then(data => {
// 确保 data 是数组并赋值给 formData.value.list
const fetchedData = Array.isArray(data) ? data : [];
formData.value.list = [...formData.value.list, ...fetchedData];
formData.value.list.push(row); // 添加新条目到列表中
console.log('Updated list:', formData.value.list);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
- 另一种更现代和清晰的方法是使用
async/await
const handleAdd = async () => {
if (props.formType === 'detail') return // 禁用按钮
const row = {
id: undefined,
shipName: undefined,
voyage: undefined,
billNumber: undefined,
boxNumber: undefined,
boxSize: undefined,
boxType: undefined,
productName: undefined,
hazardousLevel: undefined,
hazardCode: undefined,
isOpentopOrHigh: undefined,
appointmentId: undefined,
}
row.appointmentId = props.appointmentId
try {
// 调用API并等待结果
const data = await AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId);
// 确保 data 是数组并赋值给 formData.value.list
const fetchedData = Array.isArray(data) ? data : [];
formData.value.list = [...formData.value.list, ...fetchedData];
formData.value.list.push(row); // 添加新条目到列表中
console.log('Updated list:', formData.value.list);
} catch (error) {
console.error('Error fetching data:', error);
}
}