1、简单来讲就是把函数变为异步操作的
async function demo() { let result = Math.random(); console.log(result); }
2、async的第一个作用就是可以用then,执行结束再进行别的操作
demo().then(val => { console.log(val);// 123 });
3、async的下一个操作就是要结合await进行的操作,简单来讲就是必须等到await结束才进行下面的操作
function sleep(second) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(' enough sleep~'); }, second); }) } function normalFunc() { console.log('normalFunc'); } async function awaitDemo() { await normalFunc(); console.log('something, ~~'); let result = await sleep(2000); console.log(result);// 两秒之后会被打印出来 } awaitDemo();
4、async的并行操作,因为使用await的话只会一步一步的执行,如果要多个共同完成才执行的操作要用到await Promise.all([a,b,c])
async function correctDemo() { let p1 = sleep(1000); let p2 = sleep(1000); let p3 = sleep(1000); await Promise.all([p1, p2, p3]); console.log('clear the loading~'); } correctDemo();// clear the loading~