1.在函数之间加上async意味着:函数将返回一个Promise
async f() { return '444'; }, f().then(res=>{ console.log(res) //打印444 });
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()
再看过明了的:
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()
浏览器打印:
来源:博客园
作者:lwming
链接:https://www.cnblogs.com/lwming/p/11504049.html