js等待某方法执行完毕再执行

  • 之前的样子
const onOpen = (record) => {
	selectProjectList()
	selectTypeList()
	visible.value = true
	if (record) {
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
		formData.value.inspectionType = formData.value.inspectionType.replace(/(-?\d+)/g, '"$1"')
		formData.value.inspectionType = JSON.parse(formData.value.inspectionType)

		selectTypeListOn(formData.value.inspectionType);
	}
}

const selectTypeList = () => {
	typeList.value = [];
	tComputerInspectionTypeApi.list().then(res => {
		res.forEach(i => {
			const newI = {
				value: i.pkId,
				label: i.inspectionTypeName,
				list: i.inspectionDetail,
			};
			typeList.value.push(newI)
		})
	})
}
  • 修改后
const onOpen = async (record) => {
	selectProjectList()
	await selectTypeList()
	visible.value = true
	if (record) {
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
		formData.value.inspectionType = formData.value.inspectionType.replace(/(-?\d+)/g, '"$1"')
		formData.value.inspectionType = JSON.parse(formData.value.inspectionType)

		selectTypeListOn(formData.value.inspectionType);
	}
}

// 逻辑外嵌套了一层, 这样就可以使用await关键字, await必须在async函数内才能使用
const selectTypeList = () => {
	return new Promise((resolve, reject) => {
        // 嵌套的逻辑
		typeList.value = [];
		tComputerInspectionTypeApi.list().then(res => {
			res.forEach(i => {
				const newI = {
					value: i.pkId,
					label: i.inspectionTypeName,
					list: i.inspectionDetail,
				};
				typeList.value.push(newI)
			})
			resolve(); // 异步操作完成后解决Promise
		}).catch(error => {
			reject(error); // 异步操作出错时拒绝Promise
		});
	})
}
posted @ 2024-01-17 16:28  烟熏咸鱼干  阅读(733)  评论(0编辑  收藏  举报