async/await 使用

匿名 (未验证) 提交于 2019-12-03 00:02:01

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()

浏览器打印:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!