Js异步改类似同步(按顺序执行)
发表于:2022-04-13 | 分类: 前端
字数统计: 121 | 阅读时长: 1分钟 | 阅读量:
使用 asycn / await
使用场景:当有耗时方法执行,想让另一段代码在这段耗时代码之后执行时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let flag = 'before'
let slowFun = function(){
return new Promise(resolve => { // 返回一个 promise 对象
setTimeout(function(){
flag = 'changed'
console.log('slowFun done')
resolve() // 标志此方法完成
}, 2000)
})
}
async function doAll(){ // async 声明异步
await slowFun() // await 即等待slowFun执行完成
console.log(flag)
console.log('have waited slowFun for 2s')
}
doAll() // 执行测试
上一篇:
Vue中clearInterval失效问题
下一篇:
Json串中key值改为指定字符串