async/await 使用
1.在函数之间加上async意味着:函数将返回一个Promise
async f() { return '444'; }, f().then(res=>{ console.log(res) //打印444 });
不断的使用then()链式操作:
async f1() { return '1111'; }, async f2() { return '2222'; }, async f3() { return '3333'; }, obj() { this.f1() .then(res => { console.log(res);///111 return this.f2(); }) .then((res) => { console.log(res);///222 return this.f3(); }).then((res) => { console.log(res);///333 }); }
2.await的基本语法
async f() { let promise = new Promise((resolve, reject) => { console.log('1111') setTimeout(() => resolve("done!"), 2000) }); let result = await promise; //等待promise的resolve执行完再执行 console.log(result); // "done!" 2s后打印 }, f();
函数执行将会在 let result = await promise 这一行暂停,直到Promise返回结果,因此上述代码将会2秒后打印出done!
再看:
fn(num) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(2 * num) }, 2000); }) }, async testResult() { let first = await this.fn(30); let second = await this.fn(50); let third = await this.fn(20); console.log(first + second + third);//6s后打印出200 } this.testResult()
调用testResult 函数,它里面遇到了await, await 表示等一下,代码就暂停到这里,不再向下执行了,它等什么呢?等后面的promise对象执行完毕,然后拿到promise resolve 的值并进行返回,返回值拿到之后,它继续向下执行。
再看过明了的:
fn1() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(console.log('我是fn1,2s后输出')) }, 2000); }) }, async fn2() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(console.log('我是fn2,4s后输出')) }, 2000); }) }, async fn3() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(console.log('我是fn3,6s后输出')) }, 2000); }) }, async testResult() { let first = await this.fn1(); let second = await this.fn2(); let third = await this.fn3(); console.log('我是最后打印d'); //6s后打印出 } this.testResult()
浏览器打印:
大概的基础用法就这样