async、await学习
作用:
async、await是promise的语法糖,是为了让promise的语法变得更加舒服、简洁。
原理:
async返回的是一个promise对象,状态为已解决
async function fn() {} console.log(fn());
await类似于then,也会返回promise对象,只不过是跟async配套使用
async function fn() { // 使用await简化书写 let name = await '刘德华' console.log(name); // '刘德华' } fn(); // 相当于 new Promise(resolve => { resolve(); }) .then(v => { return '刘德华' }) .then(v => { console.log(v); // '刘德华' }) ---------------------------------------------------------------- async function fn() { // 使用await简化书写 let name = await new Promise(resolve => { setTimeout(() => { resolve('刘德华') }, 2000) }) console.log(name); // 两秒后输出 '刘德华' } fn(); // 相当于 new Promise(resolve => { resolve(); }) .then(v => { // 返回一个新的promise并把值传递给下一个then处理 return new Promise(resolve => { setTimeout(() => { resolve('刘德华') }, 2000) }) }) .then(v => { console.log(v); // 两秒后输出 '刘德华' })
async、await延时案例:
async function sheep(delay = 2000) { return new Promise(resolve => { setTimeout(() => { resolve(); }, delay) }) } async function show(arr) { for (let i of arr) { await sheep(1000); // 返回新的promise console.log(i); } } show([1,2,3]);
class与await结合使用案例:
class A { constructor(name) { this.name = name; } then(resolve) { resolve(this.name); } } async function getName() { let user = await new A('刘德华'); console.log(user); // 输出 '刘德华' } getName();
async、await并行执行技巧:
// 举例: let p1 = function () { return new Promise(resolve => { setTimeout(() => { resolve('梁朝伟'); }, 2000) }) } let p2 = function () { return new Promise(resolve => { setTimeout(() => { resolve('张国荣'); }, 2000) }) } async function fn() { let h1 = await p1(); console.log(h1); // 两秒后输出'梁朝伟' let h2 = await p2(); console.log(h2); // 等待上面输出后再等两秒输出'张国荣' } fn(); ---------------------------------------------------------------------- // 方式一 let p1 = function () { return new Promise(resolve => { setTimeout(() => { resolve('梁朝伟'); }, 2000) }) } let p2 = function () { return new Promise(resolve => { setTimeout(() => { resolve('张国荣'); }, 2000) }) } async function fn() { // 把他们当做普通函数调用,promise构造函数内的代码是同步代码,立即执行的 // 两个宏任务(setTimeout)会同时进入任务队列执行 // 两秒后一起改变状态 let h1 = p1(); let h2 = p2(); // await相当于then,两个then同时调用 let h1Val = await h1; let h2Val = await h2; console.log(h1Val, h2Val); // 两秒后同时输出 梁朝伟 张国荣 } fn(); --------------------------------------------------------------------- // 方式二 let p1 = function () { return new Promise(resolve => { setTimeout(() => { resolve('梁朝伟'); }, 2000) }) } let p2 = function () { return new Promise(resolve => { setTimeout(() => { resolve('张国荣'); }, 2000) }) } async function fn() { // 利用Promise.all let res = await Promise.all([p1(), p2()]); console.log(res); // 两秒后输出 ["梁朝伟", "张国荣"] } fn();