写了很久c# 突然写js 用到同步函数 踩了很多坑 原理还不是很明白,但是做出来了,做记录
用的vue`
这是实际项目中用到的 带着接口的,这个接口很耗时,要等接口返回值后 根绝返回的值做后面的功能
async function test3() {
return agencyBox.pushCertificateInfos({
ywh: this.configData.ywh,
}).then((res) => {
var status = 2;
for( let i=0;i<res.length;i++){
let code=res[i].code;
let msg=res[i].msg;
let resultCode=res[i].resultCode;
if((code === '1'&& msg.includes("该证照类型已存在编号为"))||(code === '0' && resultCode === 'A000')){
//成功
status = 1;
console.log('111111');
this.$message.success('推送电子证照成功!');
}else if (code === '11') {
status = 1;
console.log('222222');
this.$message.success('推送电子证照成功!');
}else{
//失败
status = 2;
console.log('333333');
this.$message.warning('推送电子证照失败!');
}
}
return Promise.resolve(status);
});
}
async function init() {
let success = await test3();
console.log('success',success);
}
init();
下面这个是可以直接跑起来做测试的 更直观
function test1() {
return new Promise(resolve => {
setTimeout(() => resolve("test1"), 2000);
});
}
function test2() {
console.log("test2");
}
async function test3() {
const result = await new Promise(resolve => {
setTimeout(() => resolve("test1"), 3000);
});
console.log(result);
return 1
}
async function aaa() {
let success = await test3();
console.log('success',success);
}
aaa()
这个是很久之前写的同步函数 也是实际项目的 具有一定的参考意义
async function asyncAwaitFn(route) {
return await new Promise((resolve, reject) => {
route.push({ path: '/', query: { types: types, userid: userId }})
const routeUrl = route.resolve({
path: '/dashboard',
query: {
types: types, userid: userId
}
})
resolve(routeUrl)
})
}
async function asyncAwaitFf(routeUrl) {
function timer(interval) {
var wlh = window.location.href
if (wlh.indexOf('types') > 0 && wlh.indexOf('userid') > 0) {
window.location.reload()
clearInterval(interval)
}
}
return await new Promise((resolve, reject) => {
if (routeUrl.href.indexOf('types') > 0 && routeUrl.href.indexOf('userid') > 0) {
var interval = setInterval(timer(interval), 10)
} else {
Cookies.set('company', company_old)
Cookies.set('role', role_old)
Cookies.set('entuserid', entuserid_old)
}
})
}
const serialFn = async() => { // 串行执行
const routeUrl = await asyncAwaitFn(this.$router)
await asyncAwaitFf(routeUrl)
}
serialFn()