需求:点击发送时先执行完temSaveOperation()方法再去执行sendCgOperation()方法。
// 点击暂存执行操作
temSaveOperation() {
return new Promise((resolve, reject) => {
const _route = this.$route;
this.templateId = _route.params.templateId;
if (_route.query && _route.query.id) {
// 在原有草稿上进行编辑,只向后台发送新增文件
this.addBqContent(resolve, reject);
} else {
// 新增便签
this.newBq(resolve, reject);
}
});
},
// 新建便签
newBq(resolve, reject) {
// 新建 ajax 配置
const newBqAjaxOptions = {
};
// 如果是第一次点击暂存就新增一条数据
if (!this.isClickTemSave) {
// 获取数据
this.requestNewBq(newBqAjaxOptions)
.then(data => {
resolve(data);
})
.catch((error) => {
reject(error);
});
// 已经点击过暂存
this.setClickTemSave(true);
} else {
// 不是第一次点击,则只向后台发送新增文件
this.addBqContent();
}
},
// 设置是否点击过暂存
setClickTemSave(isClickTemSave) {
this.isClickTemSave = isClickTemSave;
},
// 增加便签内容
addBqContent(resolve, reject) {
// 增加内容 ajax 配置
const addBqContentAjaxOptions = {
};
// 获取数据
this.requestAddBqContent(addBqContentAjaxOptions)
.then((data) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
},
sendCg() {
// 暂存
this.temSaveOperation()
.then(() => {
// 发送
this.sendCgOperation();
});
},
或者:
async sendCg() {
// 暂存
await this.temSaveOperation();
// 发送
this.sendCgOperation();
},
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var data = '';
async function a() {
await b();
d();
}
function b() {
return new Promise((resolve, reject) => {
c(resolve, reject);
})
}
function c(resolve, reject) {
setTimeout(() => {
data = '张三';
resolve();
}, 1000);
}
function d() {
console.log('data:', data);
}
a();
</script>
</body>
</html>